DEV Community

Cover image for Mastering Serverless with AWS SAM
Márcio Coelho
Márcio Coelho

Posted on • Edited on

2

Mastering Serverless with AWS SAM

AWS Lambda is a serverless compute service that lets you run code without provisioning or managing servers. AWS SAM (Serverless Application Model) is an open-source framework that makes building and deploying serverless applications easier. In this guide, we will walk through setting up an AWS Lambda function using Node.js and AWS SAM.

Step 1: Create a New AWS SAM Application

To begin, open a terminal and run:

sam init
Enter fullscreen mode Exit fullscreen mode

Select the following options when prompted:

Template source: AWS Quick Start Templates

Runtime: nodejs22.x (or latest available)

Package type: Zip

Project name: aws-sam-node-lambda

Once completed, navigate to the project directory:

cd aws-sam-node-lambda
Enter fullscreen mode Exit fullscreen mode

Step 2: Understanding the Project Structure

Your SAM project contains several files and folders:

aws-sam-node-lambda/
├── functions
│   ├──hello-world/
│      ├── app.js         # Lambda function code
│      ├── package.json   # Node.js dependencies
│      ├── tests/         # Unit tests
├── template.yaml       # AWS SAM template defining resources
Enter fullscreen mode Exit fullscreen mode

The template.yaml file is crucial as it defines your AWS resources.

Step 3: Writing the Lambda Function

Modify hello-world/app.js to:

exports.lambdaHandler = async (event, context) => {
    return {
        statusCode: 200,
        body: JSON.stringify({
            message: "Hello from AWS Lambda with Node.js and SAM!"
        })
    };
};
Enter fullscreen mode Exit fullscreen mode

Step 4: Build and Test Locally

Before deploying, build the function:

sam build
Enter fullscreen mode Exit fullscreen mode

To invoke it locally:

sam local invoke HelloWorldFunction
Enter fullscreen mode Exit fullscreen mode

Expected output:

{
    "statusCode": 200,
    "body": "{\"message\":\"Hello from AWS Lambda with Node.js and SAM!\"}"
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)