Published at Jul 23, 2023

AWS Lambda Function with Response Streaming using Node.js

AWS Lambda is a great service for running code without provisioning servers. In this post, we’ll look at how to create a Lambda function that returns a text using the response streaming.

Table of Contents

Getting Started

First, log into the AWS Console and create a new Lambda function called “aws-stream.”

Next, switch to your code editor and initialize a new npm project.

mkdir ~/aws-stream
cd ~/aws-stream
npm init

Create a new file called index.mjs.

Head over to package.json file and add “type”: “module” to enable ES modules. Also, I have added some scripts to help deploy to AWS.

"cleanup": "rm -rf aws-stream.zip",
"build-zip": "npm run cleanup && zip -r9q aws-stream.zip .",
"deploy": "npm ci && npm run build-zip && aws lambda update-function-code --function-name aws-stream --zip-file fileb://aws-stream.zip"

Building the Lambda Function

In index.mjs, create an async Lambda handler function. Import StreamifyResponse and initialize an responseStream. This will allow us to stream the response.

export const handler = awslambda.streamifyResponse(
  async (event, responseStream) => {

  });
);

Add a try/catch block to handle errors. Using the HttpResponseStream method, create the response stream with metadata like headers and status code.

const responseMetadata = {
  statusCode: 200,
  headers: {
  "Content-Type": "application/json",
  },
};

responseStream = awslambda.HttpResponseStream.from(
  responseStream,
  responseMetadata
);

At this point, We’ll write some text to the response stream using responseStream.write() method. This is where you can customize the content based on your app’s requirements.

const content = "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.";

responseStream.write(content);

Make sure to catch any errors and end the response stream properly.

// end response stream
responseStream.end();

Deploying the Function

With the code complete, deploy the Lambda function using the script we added earlier.

npm run deploy

Check the AWS Console to confirm the code is updated correctly. Run a test to verify it works as expected.

Note: If you’re going to stream long responses, increase the timeout from 3 seconds to 30 seconds.

Congratulations. We now have a Lambda function that can stream text responses.

Video Tutorial: