Send Message to SQS from AWS Lambda using Node js 18

Send Message to SQS from AWS Lambda using Node js 18

Send Message to SQS from AWS Lambda using Node js 18

Sending messages to an SQS or Simple Queue Service from AWS lambda is a very common requirement while working with a serverless application. In this post, I will show you how to send message to SQS from AWS lambda using node.js 18.

Node.js 18: Node.js 18 is the latest long-term support (LTS) release of Node.js. On 18th Nov 2022, AWS lambda announced the support for Node.js 18 as both a managed runtime and a container base image.

That’s nice.

But do you know that there is a slight difference between how you code your Node.js 18 lambda and the previous versions? So stay tuned with me till the end to know what changed.

Alright?

Let’s start.

Don’t want to miss any posts from us? join us on our Facebook group, and follow us on Facebook, Twitter, LinkedIn, and Instagram. You can also subscribe to our newsletter below to not miss any updates from us.


What’s so Special about AWS Lambda using Node js 18

1. Includes AWS SDK for Javascript V3: Lambda’s Node.js runtime included AWS SDK for Javascript v2 till Node.js 16. However, Lambda’s Node.js runtime 18 includes AWS SDK for Javascript v3 instead of v2.

That means you have to write your code as per v3 SDK. You can still use v2 SDK if you yourself deploy the SDK v2 with your lambda function.

But I feel why to increase the size of the deployment package unnecessarily. If I am using Node.js 18, I would be happy to go for SDK v3 as it provides quite a lot of benefits over SDK v2.

If you are new to AWS SDK for Javascript version 3, I highly recommend you have a look at official documentation first.

2. ECMAScript modules: ECMAScript modules are becoming the standard way to package JavaScript code for reuse. If you notice, the lambda created with Node.js 18 will have a handler file index.mjs.

A file with . mjs extension is a JavaScript source code file that is used as an ECMA Module (ECMAScript Module) in Node. js applications

So you can edit this file and write your code. Please note that in this newer way, you will be using  import and export instead of require.

Read more about ECMA Module here.

Steps to Send Message to SQS from AWS Lambda using Node js 18

  1. Create an SQS Queue
  2. Create a Lambda Function using Node.js
  3. Provide Permission to Lambda to Send Messages to SQS Queue
  4. Change the code to send a message to the queue
  5. Test the lambda function
  6. Verify Messages in SQS

Let’s start.

Step 1: Create an SQS Queue

If you already have an SQS queue in which you want to send a message from your lambda, you can move straight ahead with step 2. If not continue with this step.

Login to AWS Management Console, search and open SQS.

Click on Create queue

Type: Standard

Name: lambda-sqs-demo-queue

Send Message to SQS from AWS Lambda using Node js

Leave the rest of the configuration as default and click on Create queue.

Queue created successfully

The queue is created successfully.

See the queue details and grab the queue URL and queue Arn and save it for later. We will need it later.

SQS Queue URL = https://sqs.us-east-1.amazonaws.com/123456789012/lambda-sqs-demo-queue

SQS Arn = arn:aws:sqs:us-east-1:123456789012:lambda-sqs-demo-queue

Note: Please note that I have changed the accountId due to security reasons. So use the actual URL and Arn of the queue you create.

Step 2: Create a Lambda Function using Node.js 18

Navigate to the Lambda console and click Create function.

Select the Author from scratch option

Provide basic info like function name and select runtime as Node.js 18.x. Leave the permission and role details as it is. Scroll down and click Create function.

Send Message to SQS from AWS Lambda using Node js 4

Your lambda function gets created successfully.

Step 3: Provide Permission to Lambda to Send Messages to SQS Queue

AWS lambda by default doesn’t have access to SQS service. So, you need to provide send message permission to lambda so that it can send a message to the queue on your behalf.

Click on the Configuration tab of your lambda and click on Permissions as shown below-

Send Message to SQS from AWS Lambda using Node js 5

Click on the role name link. Once you click on the role name, you are navigated to the IAM dashboard. You will see the permission for basic execution there. I will leave that as it is as I don’t prefer to edit this.

Click on Add Permission.

You will see two options-

  • Attach policy
  • Create Inline policy

Click on create inline policy and paste the below JSON(of course after changing the queue Arn as yours will be different).

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Effect": "Allow",
            "Action": [
              "sqs:SendMessage"
            ],
            "Resource": "arn:aws:sqs:us-east-1:123456789012:lambda-sqs-demo-queue"
        }
    ]
}

Click on Review policy.

Provide a name for the policy and click Create policy.

The policy gets created and attached to the lambda function role. Now we are all ready to send messages to SQS from lambda.

Step 4: Change the Code to Send Message to SQS from AWS Lambda using Node js 18

Navigate to the Code tab and paste the below code into index.mjs file.

Notice as we using node.js 18, ECMAScript module style extension is used. Also instead of require, we are using import. Using require will not work for it.

import { SQSClient, SendMessageCommand } from "@aws-sdk/client-sqs";
const sqsClient = new SQSClient({ region: "us-east-1" });

export const handler = async (event) => {
  let response;

  const params = {
    DelaySeconds: 10,
    MessageAttributes: {
      Author: {
        DataType: "String",
        StringValue: "Preeti",
      }
    },
    MessageBody: "Welcome to CloudKatha",
    QueueUrl: "https://sqs.us-east-1.amazonaws.com/672607396920/lambda-sqs-demo-queue"
  };


  try {
    const data = await sqsClient.send(new SendMessageCommand(params));
    if (data) {
      console.log("Success, message sent. MessageID:", data.MessageId);
      const bodyMessage = 'Message Send to SQS- Here is MessageId: ' +data.MessageId;
      response = {
        statusCode: 200,
        body: JSON.stringify(bodyMessage),
      };
    }else{
      response = {
        statusCode: 500,
        body: JSON.stringify('Some error occured !!')
      };
    }
    return response;
  }
  catch (err) {
    console.log("Error", err);
  }

};

Code Explanation:

Import:

import { SQSClient, SendMessageCommand } from "@aws-sdk/client-sqs";

AWS SDK v3 is more modular and allows you to pull only what’s needed instead of the whole SDK.

Here we are importing the SQS client and the SendMessageCommand as that is what we need for this tutorial.

Client creation:

const sqsClient = new SQSClient({ region: "us-east-1" });

In this line, we are instantiating the SQS client passing region. You can decide to not pass the region as well in that case the default region you provided while setting up your CLI or credential will be used.

And you will define your client like-

const sqsClient = new SQSClient({ });

Parameters to SendMessageCommand

Next, we are defining some of the parameters that SendMessageCommand expects. These parameters are self-explanatory. You can check the documentation to see all the parameters.

const params = {
    DelaySeconds: 10,
    MessageAttributes: {
      Author: {
        DataType: "String",
        StringValue: "Preeti",
      }
    },
    MessageBody: "Welcome to CloudKatha",
    QueueUrl: "https://sqs.us-east-1.amazonaws.com/123456789012/lambda-sqs-demo-queue"
  };

As you saw, we have set up a few important parameters like QueueUrl in which to send messages, MessageBody, MessageAttributes etc.

Code to Send the message

We have parameter ready to pass to SendMessageCommand. Let’s send the meesage.

 const data = await sqsClient.send(new SendMessageCommand(params));

This line sends the command for sending messages with specified parameters to the queue specified in QueueUrl. And it returns the result that includes MessageId and others that you can see by doing a simple console.log(data) statement.

Step 5: Test the lambda function

Once you have pasted the code, click on Deploy as you need to deploy your changes to see the results.

Click on Test beside Deploy(You can even go to Test tab for testing)

In the Configure test event screen, provide an Event name and provide a simple Event JSON as shown. Scroll down and click save

Send Message to SQS from AWS Lambda using Node js 18 3 updated

Click on Test again

As you can see, the message is sent to the SQS queue successfully from our lambda function and the message id is returned in the response.

Send Message to SQS from AWS Lambda using Node js 18 4

Step 6: Verify Messages in SQS

Navigate to SQS or simple queue service in the AWS console.

Send Message to SQS from AWS Lambda using Node js 18 5

Let’s see the message details

Click on the queue name –> Click Send and receive messages –> Scroll down to Receive messages section –> Click poll for messages –> click on the ID for the shown messages.

And this is how the message looks

message details

Click on the Details and Attributes tab to see those details.

Message Attributes:

Message Attribute

Message Details

Message details

Conclusion

In this post, we learnt how to send message to SQS from AWS lambda using node js 18. We also saw that lambda node.js runtime 18 contains AWS SDK for Javascript v3. This means you either need to write the v3-compliant code or ship AWS SDK for Javascript v2 with lambda.

Anyway, v3 of SDK is modular and results in better performance. So I went ahead with v3 SDK only.

I hope you found this post helpful. Feel free to drop your questions in the comment section.

Enjoyed the content?

Subscribe to our newsletter below to get awesome AWS learning materials delivered straight to your inbox.

Don’t forget to motivate me by-

  • Adding a comment below on what you liked and what can be improved.
  • Follow us on
  • Share this post with your friends

Suggested Read:

2 thoughts on “Send Message to SQS from AWS Lambda using Node js 18

Leave a Reply

Your email address will not be published. Required fields are marked *