Subscribe
Building a Serverless Application with Node.js and AWS
6 mins read

By: vishwesh

Building a Serverless Application with Node.js and AWS

In recent years, serverless architecture has gained significant popularity due to its scalability, cost-efficiency, and reduced operational overhead. AWS (Amazon Web Services) provides a powerful suite of services that allows developers to build serverless applications easily. In this article, we will explore how to build a serverless application using Node.js and AWS.

Prerequisites

Before diving into building a serverless application, you should have some basic knowledge of Node.js and AWS services such as AWS Lambda, API Gateway, and S3.

Overview of a Serverless Application

A serverless application is an application where the infrastructure management is abstracted away, and developers can focus solely on writing code. AWS Lambda is a key component of building serverless applications, as it allows you to run your code without provisioning or managing servers.

The serverless application we'll be building is a simple image recognition service. Users will be able to upload an image to the application, and it will return a response with the labels that describe the contents of the image.

Step 1: Set Up AWS Account and Tools

To get started, you'll need an AWS account. If you don't have one, you can create a free account on the AWS website. Once you have an account, make sure you have the AWS CLI (Command Line Interface) installed on your machine. The AWS CLI allows you to interact with various AWS services from the command line.

After installing the AWS CLI, configure it with your AWS credentials by running the following command:

$ aws configure

You'll need to provide your AWS Access Key ID, Secret Access Key, default region, and output format.

Step 2: Create an S3 Bucket

In our application, we need a place to store the uploaded images. AWS provides Simple Storage Service (S3), which is an object storage service. Let's create an S3 bucket to store our images.

  1. Open the AWS Management Console.
  2. Navigate to the S3 service.
  3. Click on the "Create bucket" button.
  4. Provide a unique name for your bucket and choose the region.
  5. Leave the default settings for the rest of the options and click "Create bucket."

Step 3: Create a Lambda Function

Next, we'll create a Lambda function that will handle the image recognition logic. Follow these steps:

  1. Open the AWS Management Console.
  2. Navigate to the Lambda service.
  3. Click on the "Create function" button.
  4. Choose the "Author from scratch" option.
  5. Provide a name for your function and select Node.js 14.x as the runtime.
  6. Under "Permissions," choose an existing role or create a new one with the necessary permissions to access S3.
  7. Click "Create function."

Step 4: Write the Lambda Function

Now that we have our Lambda function, let's write the code to handle the image recognition.

In the Lambda function's code editor, replace the default code with the following Node.js code:

const AWS = require('aws-sdk');
const { v4: uuidv4 } = require('uuid');

const rekognition = new AWS.Rekognition();
const s3 = new AWS.S3();

exports.handler = async (event) => {
  const bucketName = 'your-s3-bucket-name';
  const imageName = `${uuidv4()}.jpg`;

  const image = Buffer.from(event.body, 'base64'); // Assuming the image data is passed in the request body as base64 encoded string

  const s3Params = {
    Bucket: bucketName,
    Key: imageName,
    Body: image,
  };

  await s3.putObject(s3Params).promise();

  const rekognitionParams = {
    Image: {
      S3Object: {
        Bucket: bucketName,
        Name: imageName,
      },
    },
    MaxLabels: 5,
    MinConfidence: 70,
  };

  const response = await rekognition.detectLabels(rekognitionParams).promise();

  const labels = response.Labels.map((label) => label.Name);

  return {
    statusCode: 200,
    body: JSON.stringify({ labels }),
  };
};

Let's go through the code step by step:

  • We import the necessary AWS SDK modules and the uuidv4 function from the uuid package.
  • We create instances of the AWS Rekognition service and the S3 service.
  • Our Lambda function is an async function named handler that takes an event parameter.
  • We define the bucketName variable, which should be set to the name of the S3 bucket you created earlier.
  • We generate a unique image name using the uuidv4 function and the .jpg file extension.
  • We convert the image data from base64 to a Buffer object.
  • We define the s3Params object, which specifies the bucket name, image name, and image data for uploading to S3 using the putObject method.
  • We use await to ensure the image is uploaded to S3 before continuing.
  • We define the rekognitionParams object, which specifies the image to analyze, the maximum number of labels to return (MaxLabels), and the minimum confidence level for the labels (MinConfidence).
  • We use the detectLabels method of the Rekognition service to perform the image recognition and store the result in the response variable.
  • We extract the label names from the response object and store them in the labels array.
  • Finally, we return a response with a status code of 200 and the labels as a JSON string in the response body.

Step 5: Configure API Gateway

To expose our Lambda function as a RESTful API, we'll use API Gateway, which is a fully managed service by AWS. Here's how you can configure API Gateway:

  1. Open the AWS Management Console.
  2. Navigate to the API Gateway service.
  3. Click on the "Create API" button.
  4. Choose the "REST" protocol and click on the "Build" button.
  5. Under "Create new API," select "New API."
  6. Provide a name for your API and select the appropriate region.
  7. Click on the "Create API" button.

Step 6: Create an API Resource and Method

Once you've created the API, follow these steps to create a resource and method:

  1. Click on the "Actions" dropdown and select "Create Resource."

  2. Provide a name for your resource (e.g., "image").

  3. Select the newly created resource and click on the "Create Resource" button.

  4. With the newly created resource selected, click on the "Actions" dropdown again and select "Create Method."

  5. Choose the HTTP method you want to use (e.g., POST) and click on the checkmark button.

  6. In the "Integration Type" section, select "Lambda Function" and choose the Lambda function you created earlier.

  7. Click on the "Save" button.

Step 7: Deploy the API

To make your API accessible, you need to deploy it. Here's how:

  1. With your API selected in the API Gateway console, click on the "Actions" dropdown and select "Deploy API."
  2. In the "Deployment stage" section, choose "New Stage."
  3. Provide a name for your stage (e.g., "dev") and click on the "Deploy" button.

After successful deployment, you will see the "Invoke URL" for your API. Take note of this URL as we will use it to test our serverless application.

Step 8: Test the Serverless Application

To test your serverless application, you can use tools like cURL or Postman. Follow these steps to test the image recognition service:

  1. Send a POST request to the Invoke URL of your API's endpoint.
  2. Set the request body to contain the image data as a base64 encoded string.
  3. Make sure to set the "Content-Type" header to "application/json".

Here's an example cURL command to test the service:

$ curl -X POST -H "Content-Type: application/json" -d '{"body": "base64-encoded-image-data"}' https://your-api-gateway-url/dev/image

Replace "base64-encoded-image-data" with the actual base64 encoded image data.

If everything is set up correctly, you should receive a response with the detected labels in the JSON format.

Conclusion

Congratulations! You have successfully built a serverless application using Node.js and AWS. We covered the essential steps, from setting up the AWS account and tools to deploying the serverless application using Lambda, API Gateway, and S3. Remember, serverless architecture offers scalability, reduced operational overhead, and cost-efficiency, making it an excellent choice for many applications. Keep exploring the AWS services and possibilities to unleash the full potential of serverless development. Happy coding!

Recent posts

Don't miss the latest trends

    Popular Posts

    Popular Categories