You are currently viewing Creating and Deploying an AWS Lambda with Node.js and DynamoDB using AWS SAM
  • Post category:AWS
  • Post comments:0 Comments
  • Reading time:74 mins read

In this tutorial, you’ll learn how to create a simple AWS Lambda function in Node.js, query data from a DynamoDB table, define the Lambda in a SAM template.yaml and deploy the Lambda with AWS SAM CLI.


    1. Prerequisites

    Before starting, make sure you have:

    • An AWS account
    • AWS CLI installed and configured (aws configure)
    • AWS SAM CLI installed (docs)
    • Node.js (v16 or higher recommended)

    2. Project Setup

    Create a new project folder:

    ShellScript
    mkdir sam-dynamodb-lambda
    cd sam-dynamodb-lambda
    sam init
    

    Choose:

    • Runtime: nodejs18.x
    • Package type: Zip
    • Template: Hello World Example

    This will scaffold a project.


    3. DynamoDB Table Setup

    For our example, let’s create a table called BooksTable with id as the primary key:

    ShellScript
    aws dynamodb create-table \
      --table-name BooksTable \
      --attribute-definitions AttributeName=id,AttributeType=S \
      --key-schema AttributeName=id,KeyType=HASH \
      --provisioned-throughput ReadCapacityUnits=5,WriteCapacityUnits=5
    

    Insert some sample data:

    ShellScript
    aws dynamodb put-item \
      --table-name BooksTable \
      --item '{"id": {"S": "1"}, "title": {"S": "AWS Lambda in Action"}, "author": {"S": "John Developer"}}'
    
    aws dynamodb put-item \
      --table-name BooksTable \
      --item '{"id": {"S": "2"}, "title": {"S": "Serverless Made Simple"}, "author": {"S": "Jane Doe"}}'
    

    4. Lambda Function Code

    Navigate into the function folder hello-world (generated by SAM) and update app.js:

    JavaScript
    // app.js
    const AWS = require("aws-sdk");
    const dynamodb = new AWS.DynamoDB.DocumentClient();
    const TABLE_NAME = process.env.TABLE_NAME;
    
    exports.lambdaHandler = async (event) => {
      try {
        // If an id is provided in query params, fetch a single book
        if (event.queryStringParameters && event.queryStringParameters.id) {
          const id = event.queryStringParameters.id;
          const result = await dynamodb
            .get({
              TableName: TABLE_NAME,
              Key: { id },
            })
            .promise();
    
          return {
            statusCode: 200,
            body: JSON.stringify(result.Item || {}),
          };
        }
    
        // Otherwise, scan all items
        const result = await dynamodb.scan({ TableName: TABLE_NAME }).promise();
    
        return {
          statusCode: 200,
          body: JSON.stringify(result.Items),
        };
      } catch (err) {
        return {
          statusCode: 500,
          body: JSON.stringify({ error: err.message }),
        };
      }
    };

    5. SAM Template

    Update your template.yaml to include DynamoDB table and environment variable:

    XML
    AWSTemplateFormatVersion: '2010-09-09'
    Transform: AWS::Serverless-2016-10-31
    Description: >-
      SAM Template for Lambda + DynamoDB example
    
    Globals:
      Function:
        Timeout: 5
        Runtime: nodejs18.x
    
    Resources:
      BooksTable:
        Type: AWS::DynamoDB::Table
        Properties:
          TableName: BooksTable
          AttributeDefinitions:
            - AttributeName: id
              AttributeType: S
          KeySchema:
            - AttributeName: id
              KeyType: HASH
          ProvisionedThroughput:
            ReadCapacityUnits: 5
            WriteCapacityUnits: 5
    
      GetBooksFunction:
        Type: AWS::Serverless::Function
        Properties:
          CodeUri: hello-world/
          Handler: app.lambdaHandler
          Environment:
            Variables:
              TABLE_NAME: !Ref BooksTable
          Policies:
            - DynamoDBReadPolicy:
                TableName: !Ref BooksTable
          Events:
            ApiEvent:
              Type: Api
              Properties:
                Path: /books
                Method: get
    

    6. Build and Deploy

    Run:

    ShellScript
    sam build
    sam deploy --guided
    

    Follow the prompts:

    • Stack name: books-lambda-stack
    • AWS region: us-east-1 (or your region)
    • Accept defaults

    After deployment, SAM will output an API Gateway URL.


    7. Test the Lambda

    Get all books:

    ShellScript
    curl https://<your-api-gateway-url>/books
    

    Get a single book by id:

    ShellScript
    curl "https://<your-api-gateway-url>/books?id=1"
    

    Conclusion

    You’ve just created a fully working AWS Lambda function in Node.js that:

    • Reads from a DynamoDB table
    • Is defined and deployed via AWS SAM
    • Is accessible through API Gateway

    This approach is scalable, repeatable, and production-ready.

    Please follow and like us:

    Leave a Reply