DEV Community

Cover image for Introduction to Serverless Computing with AWS: A Deep Dive with Node.js
Eslam Genedy
Eslam Genedy

Posted on

3 1

Introduction to Serverless Computing with AWS: A Deep Dive with Node.js

Serverless computing is a game-changer for modern application development, and AWS Lambda is at the forefront of this revolution. By leveraging AWS Lambda, developers can build scalable, event-driven applications without worrying about server management. In this article, we’ll explore serverless computing with AWS services, focusing on AWS Lambda, API Gateway, and DynamoDB, with practical Node.js code samples.

What is AWS Lambda?

AWS Lambda is a serverless compute service that runs your code in response to events and automatically manages the underlying compute resources. You can use Lambda to build applications that respond quickly to new information, scale automatically, and only incur costs when your code is running.

Key Features of AWS Lambda:

  • Event-Driven: Lambda functions are triggered by events from AWS services like S3, DynamoDB, API Gateway, and more.
  • Automatic Scaling: Lambda automatically scales your application by running code in response to each trigger.
  • Pay-as-You-Go: You are charged only for the compute time your code consumes, measured in milliseconds.

AWS Services for Serverless Applications

To build a complete serverless application, you’ll often use a combination of AWS services:

  1. AWS Lambda: For running your code.
  2. API Gateway: To create RESTful APIs that trigger Lambda functions.
  3. DynamoDB: A fully managed NoSQL database for storing application data.
  4. IAM (Identity and Access Management): To manage permissions for your Lambda functions and other AWS resources.

Building a Serverless Application with AWS and Node.js

Let’s build a simple serverless application using AWS Lambda, API Gateway, and DynamoDB. The application will allow users to:

  1. Create a new item in a DynamoDB table.
  2. Retrieve all items from the DynamoDB table.

Prerequisites:

  • An AWS account.
  • AWS CLI installed and configured.
  • Node.js installed.

Step 1: Set Up a DynamoDB Table

  1. Go to the DynamoDB console in AWS.
  2. Click Create Table.
  3. Name the table Items and set the primary key as id (String).
  4. Click Create.

Step 2: Create an IAM Role for Lambda

  1. Go to the IAM console.
  2. Create a new role with the following permissions:
    • AmazonDynamoDBFullAccess
    • AWSLambdaBasicExecutionRole
  3. Attach this role to your Lambda functions.

Step 3: Create a Lambda Function to Add Items to DynamoDB

  1. Go to the Lambda console.
  2. Click Create Function.
  3. Name the function addItem.
  4. Choose Node.js 18.x as the runtime.
  5. Under Permissions, attach the IAM role you created earlier.

Here’s the Node.js code for the addItem function:

const AWS = require('aws-sdk');
const dynamoDb = new AWS.DynamoDB.DocumentClient();

exports.handler = async (event) => {
    const { id, name } = JSON.parse(event.body);

    const params = {
        TableName: 'Items',
        Item: { id, name },
    };

    try {
        await dynamoDb.put(params).promise();
        return {
            statusCode: 200,
            body: JSON.stringify({ message: 'Item added successfully' }),
        };
    } catch (error) {
        return {
            statusCode: 500,
            body: JSON.stringify({ error: 'Could not add item' }),
        };
    }
};
Enter fullscreen mode Exit fullscreen mode

Step 4: Create a Lambda Function to Retrieve Items from DynamoDB

  1. Create another Lambda function named getItems.
  2. Use the same runtime and IAM role as before.

Here’s the Node.js code for the getItems function:

const AWS = require('aws-sdk');
const dynamoDb = new AWS.DynamoDB.DocumentClient();

exports.handler = async () => {
    const params = {
        TableName: 'Items',
    };

    try {
        const data = await dynamoDb.scan(params).promise();
        return {
            statusCode: 200,
            body: JSON.stringify(data.Items),
        };
    } catch (error) {
        return {
            statusCode: 500,
            body: JSON.stringify({ error: 'Could not retrieve items' }),
        };
    }
};
Enter fullscreen mode Exit fullscreen mode

Step 5: Set Up API Gateway

  1. Go to the API Gateway console.
  2. Click Create API and choose HTTP API.
  3. Add two routes:
    • POST /items to trigger the addItem Lambda function.
    • GET /items to trigger the getItems Lambda function.
  4. Deploy the API to a stage (e.g., prod).

Step 6: Test the Application

You can use tools like Postman or curl to test your API.

Add an Item:

curl -X POST https://<api-id>.execute-api.<region>.amazonaws.com/prod/items \
-H "Content-Type: application/json" \
-d '{"id": "1", "name": "Sample Item"}'
Enter fullscreen mode Exit fullscreen mode

Retrieve Items:

curl -X GET https://<api-id>.execute-api.<region>.amazonaws.com/prod/items
Enter fullscreen mode Exit fullscreen mode

Advanced: Environment Variables and Logging

Environment Variables

You can configure environment variables in the Lambda console to store sensitive information like table names or API keys.

Logging

AWS Lambda automatically integrates with CloudWatch. Use console.log or console.error in your Node.js code to log messages:

console.log('Adding item to DynamoDB:', params);
console.error('Error adding item:', error);
Enter fullscreen mode Exit fullscreen mode

Best Practices for Serverless Development

  1. Keep Functions Small and Focused: Each Lambda function should perform a single task.
  2. Use Environment Variables: Avoid hardcoding configuration values.
  3. Monitor with CloudWatch: Set up alarms and dashboards to monitor your functions.
  4. Optimize Cold Starts: Use provisioned concurrency for time-sensitive applications.
  5. Secure Your APIs: Use IAM roles, API keys, or Cognito for authentication.

Conclusion

Serverless computing with AWS Lambda and Node.js enables developers to build scalable, cost-effective applications with minimal operational overhead. By combining AWS services like Lambda, API Gateway, and DynamoDB, you can create powerful serverless architectures that respond to events in real-time.

With the code samples and steps provided, you’re now equipped to start building your own serverless applications on AWS. Happy coding! 🚀

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

Top comments (2)

Collapse
 
moamryehia profile image
Mohamed Amr

Thank you for sharing

Collapse
 
ahtealeb82 profile image
Ahmed Tealeb

Great

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more