PWSHub News

How to install the AWS SDK v3 in Node.js

In December 2020, AWS announced the general availability of the AWS SDK v3, which improved the way developers build and deploy applications that interact with AWS services using the SDK.

Almost four years ago, the AWS SDK v2 was still widely used, with almost 10 million downloads per week (if the value is incorrect, it is because of developers that migrated after reading my post 😌); developers could benefit from a better developer experience and application performance improvements by migrating to v3.

This post will show how to install and use the AWS SDK v3 for Node.js to interact with an AWS service.

Why you should use the AWS SDK v3

The AWS SDK v3 comes with major improvements in comparison to the v2 that we can enumerate the following:

  • Modular package: Instead of publishing a single package containing all the functions for all the services, each service is now published as a Node.js package under the scope @aws-sdk. This reduces the bundle size, which is essential for platforms such as Mobile, Lambda Function, IoT, etc...
  • TypeScript support: You have a better developer experience by having typing and autocomplete and the static and runtime type check, preventing you from deploying non-functioning code in production.
  • Middleware stack: allows you to easily customize SDK behavior by adding more information in the execution context; you can add your custom asynchronous actions and/or remove default ones.
  • Active maintenance: The AWS SDK v3 is actively maintained while the v2 is still maintained but is entering the non-maintenance mode.
  • Securities patches: By being actively maintained, you will gain feature updates and also critical securities fixes and patches, which are essential for a client interacting with your services in production.

Install AWS SDK v3

The major difference with the AWS SDK v2 is that instead of installing a single package containing all the services SDK, you can install a Node.js package only for the service you need.

The package's pattern is @aws-sdk/client-<service-name>

You must refer to the AWS SDK for JavaScript V3 API Reference Guide to find the AWS service's name, which is in the left sidebar under the section "services".

Homepage of the AWS SDK for JavaScript v3.
Homepage of the AWS SDK for JavaScript v3.

Let's say you are building a backend REST API and need the SDK to interact with the following services: AWS Lambda, S3, CloudFront, SNS, SQS, and API Gateway.

Here is the command to install these packages:


npm install @aws-sdk/client-lambda \
@aws-sdk/client-s3 \
@aws-sdk/client-cloudfront \
@aws-sdk/client-sns \
@aws-sdk/client-sqs

With Yarn, it will be


yarn add @aws-sdk/client-lambda \
@aws-sdk/client-s3 \
@aws-sdk/client-cloudfront \
@aws-sdk/client-sns \
@aws-sdk/client-sqs

That is it!!! After, you must read the API reference for each service to see which methods are available and how to use them.

  • API reference for AWS Lambda client SDK v3
  • API reference for AWS S3 client SDK v3
  • API reference for AWS CloudFront client SDK v3
  • API reference for AWS SNS client SDK v3
  • API reference for AWS SQS client SDK v3

Demo with the AWS Lambda SDK client

Let's say you have your backend API, and you want to programmatically invoke a Lambda function and get the returned result. Let's see how to do that with the AWS SDK client v3

Prerequisites

To follow this tutorial, make sure you have the following tools installed on your computer.

  • An AWS account with a free tier; create an account here.
  • Node.js 18+ and Yarn - Download link
  • The AWS credentials to authenticate. Read my blog post to generate one.
  • An AWS Lambda Function deployed. Read my blog post to quickly deploy one.

Set up the project

We will use the starter template we built in this tutorial to quickly bootstrap a Node.js project with TypeScript.

Run the command below to set up the project:


git clone https://github.com/tericcabrel/node-ts-starter.git node-lambda-sdk
cd node-lambda-sdk
yarn install
yarn start

The last command will execute the project and print the outer in the console

Install the AWS Lambda SDK client v3

As we saw earlier, run this command to install the SDK


yarn add @aws-sdk/client-lambda

The Lambda SDK client requires the AWS secret key ID and the AWS secret access key to authenticate. We will read these values from the environment variables file with the help of the Node.js package dotenv.


yarn add dotenv

Create a file name .env and add the code below:


AWS_ACCESS_KEY_ID=<value>
AWS_SECRET_ACCESS_KEY=<value>

Replace the <value> with your AWS credentials.

Invoke a Lambda Function with the AWS SDK client v3

Now we can use it to invoke the Lambda Function, replace the code of the file src/index.ts with the code below:


import { configDotenv } from 'dotenv';
import { LambdaClient, InvokeCommand, InvokeCommandInput } from '@aws-sdk/client-lambda';
configDotenv();
const lambdaClient = new LambdaClient({
  credentials: {
    accessKeyId: process.env.AWS_ACCESS_KEY_ID,
    secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY,
  },
});
const main = async () => {
  const payload = {
    body: JSON.stringify({
      height: 181,
      weight: 88,
    }),
  };
  const input: InvokeCommandInput = {
    FunctionName: 'bmi-calculator',
    InvocationType: 'RequestResponse',
    Payload: JSON.stringify(payload),
  };
  try {
    const command = new InvokeCommand(input);
    const response = await lambdaClient.send(command);
    const responseString = response.Payload?.transformToString('utf-8') ?? '{}';
    console.log(JSON.parse(responseString));
  } catch (e) {
    console.error(e);
  }
};
void main();

We create an instance of the AWS Lambda SDK client with the AWS credentials and prepare the input for the command that invokes the function.

We pass the function name and indicate that we want a synchronous invocation by setting the invocation type to RequestResponse.

💡

Replace the property FunctionName with your own Lambda function name.

We invoke the function, parse the response, extract the function result, and print it in the console. The execution is wrapped in a try-catch block.

Run the command below to invoke the Lambda function:


yarn start

You will get an output similar to this one:

The output of an application using the AWS SDK v3 to invoke a Lambda Function.
The output of an application using the AWS SDK v3 to invoke a Lambda Function.

Wrap up

By using the AWS SDKv3, you will gain a better developer experience while building features and improve performance in production, thanks to the reduced bundle size.

For those having a project using the AWS SDK v2 and wanting to migrate to the AWS SDK v3, follow the migration guide.

You can find the code source on the GitHub repository.

Follow me on Twitter or subscribe to my newsletter to avoid missing the upcoming posts and the tips and tricks I occasionally share.

Source: blog.tericcabrel.com

Related stories
1 week ago - You may want to host your website on a virtual private server or a virtual machine like AWS EC2. But it can be a challenge to connect a domain name that you purchased from providers like Namecheap or Godaddy. But if you know the steps to...
3 weeks ago - React is an open-source JavaScript library that helps you build dynamic user interfaces (UIs). You can use it to build components that represent logically reusable parts of the UI. Because React is open source, anyone can access its...
1 week ago - Reading user input from the keyboard is a valuable skill for a Python programmer, and you can create interactive and advanced programs that run on the terminal. In this tutorial, you'll learn how to create robust user input programs,...
3 weeks ago - The Go programming language, also known as Golang, was developed at Google in 2007 by Robert Griesemer, Rob Pike, and Ken Thompson. It was open-sourced in 2009. Go is expressive, concise, clean, and efficient. The language is statically...
Other stories
3 hours ago - Here's a quick set of steps from my actual experiences of using Fedora Linux as daily driver, which you can follow.
7 hours ago - Written by Contributor Opinions expressed by Twilio contributors are their own In this post, we'll learn how to build an...
9 hours ago - In the world of data science, where raw information swirls in a cacophony of numbers and variables, lies the art of harmonizing data. Like a maestro conducting a symphony, the skilled data scientist orchestrates the disparate elements of...
9 hours ago - Windows 10 allows you to create a password lock on a folder so only you can access the content within. Here are the steps to set up a password-locked folder
9 hours ago - Want to mirror your iPhone screen on your Ubuntu desktop? There's a free, open-source app you can install from the Ubuntu repos to do exactly that. If
13 hours ago - Avid users of Varia, a modern download manager for Linux desktops, may want to check out official browser extensions. By installing the official Varia
13 hours ago - So far, all of my Alpine.js explorations have been client-side focused. But, my ultimate goal is to see if Alpine.js is a good companion framework for a ColdFusion-based multi-page application (MPA). As such, I wanted to spend some time...