Nov 23, 20268 min read

Use the AWS SDK for JavaScript v3 in a Node.js Backend

How the modular AWS SDK for JavaScript v3 works in a Node.js and TypeScript backend: clients and commands, the credential chain, region, retries and timeouts, paginators, typed errors, reading streamed bodies, migrating from v2 after its end of support, and which AWS calls an Encore service can drop the SDK for.

Illustration for Use the AWS SDK for JavaScript v3 in a Node.js Backend

The AWS SDK for JavaScript v3 is the SDK a Node.js backend uses for AWS now, since v2 reached end of support in September 2025. Plenty of code still calls S3 and SQS the v2 way, with one aws-sdk import and .promise(), and migrating is when timeouts and retries get revisited.

This guide covers clients, credentials, retries, timeouts, pagination and errors, then what an Encore service can drop.

How is SDK v3 structured?

Each AWS service is its own npm package, and each API operation is a command class you pass to the client's send method:

~/api
$ npm install @aws-sdk/client-s3 @aws-sdk/client-sqs

Create one configured client per service and reuse it across requests:

// aws.ts import { S3Client, GetObjectCommand } from "@aws-sdk/client-s3"; import { SQSClient, SendMessageCommand } from "@aws-sdk/client-sqs"; export const s3 = new S3Client({ region: "eu-central-1" }); export const sqs = new SQSClient({ region: "eu-central-1" }); export async function readConfig(): Promise<string> { const res = await s3.send(new GetObjectCommand({ Bucket: "acme-config", Key: "flags.json" })); return (await res.Body?.transformToString()) ?? ""; } export async function enqueue(queueUrl: string, body: object) { await sqs.send(new SendMessageCommand({ QueueUrl: queueUrl, MessageBody: JSON.stringify(body) })); }

Splitting by service keeps install and bundle sizes small, which matters most for Lambda cold starts. Every package also exports an aggregated client, such as S3, with methods like s3.getObject({...}), which reads more like v2 but pulls in every command. Create clients once at module scope and reuse them, since each client holds a pool of keep-alive connections, and creating one per request throws that pool away.

How does the SDK find credentials and region?

In Node.js, the default credential provider chain tries, in order, environment variables, SSO and shared config and credentials files, web identity tokens, ECS container credentials and the EC2 instance metadata service, so a backend should almost never pass credentials in code: locally it picks up your AWS_PROFILE, and on ECS Fargate or Lambda it uses the task or function role.

Region is separate and has no fallback to a default, so a client without region in code, AWS_REGION in the environment or a region in the shared config fails on the first call with "Region is missing". The missing region guide covers that error. Setting it in code from your own configuration is the most explicit option.

How do retries and timeouts work?

Every client retries throttling errors, 5xx responses and network failures with exponential backoff, using the standard retry mode and up to three attempts by default. maxAttempts raises or lowers that, and retryMode: "adaptive" adds client-side rate limiting that slows down after throttling, which helps a worker that hammers one DynamoDB table or SQS queue.

There is no request timeout by default, so a hung connection can block a handler until the platform kills it. Set one on the HTTP handler for the whole client, or per call with an abort signal:

// clients.ts import { S3Client, HeadObjectCommand } from "@aws-sdk/client-s3"; import { NodeHttpHandler } from "@smithy/node-http-handler"; export const s3 = new S3Client({ region: process.env.AWS_REGION ?? "eu-central-1", maxAttempts: 4, retryMode: "adaptive", requestHandler: new NodeHttpHandler({ connectionTimeout: 2_000, requestTimeout: 10_000, }), }); export async function exists(bucket: string, key: string): Promise<boolean> { try { await s3.send(new HeadObjectCommand({ Bucket: bucket, Key: key }), { abortSignal: AbortSignal.timeout(3_000), }); return true; } catch (err) { if (err instanceof Error && err.name === "NotFound") return false; throw err; } }

The request timeout applies to each attempt, so the worst case is roughly maxAttempts times the timeout plus backoff, which should fit inside the caller's own deadline. Install @smithy/node-http-handler next to the clients to import the handler.

How do you page through results?

List operations return a page and a continuation token, and each client package ships paginator functions that follow the token for you as an async iterator:

// list.ts import { paginateListObjectsV2 } from "@aws-sdk/client-s3"; import { s3 } from "./clients"; export async function totalBytes(bucket: string, prefix: string): Promise<number> { let total = 0; for await (const page of paginateListObjectsV2({ client: s3, pageSize: 1000 }, { Bucket: bucket, Prefix: prefix })) { for (const obj of page.Contents ?? []) total += obj.Size ?? 0; } return total; }

The paginator stops when the service stops returning a token, so a loop over a large bucket keeps going until it has seen every page, and an early break stops further requests.

How do you handle errors?

Service errors are thrown as exceptions with a name matching the AWS error code and a $metadata object with the HTTP status and request ID. Common errors are exported as classes, so instanceof works for them:

// get.ts import { GetObjectCommand, NoSuchKey, S3ServiceException } from "@aws-sdk/client-s3"; import { s3 } from "./clients"; export async function getText(bucket: string, key: string): Promise<string | null> { try { const res = await s3.send(new GetObjectCommand({ Bucket: bucket, Key: key })); return (await res.Body?.transformToString()) ?? null; } catch (err) { if (err instanceof NoSuchKey) return null; if (err instanceof S3ServiceException) { console.error("s3 error", err.name, err.$metadata.httpStatusCode, err.$metadata.requestId); } throw err; } }

HeadObject has no body, so a missing object comes back as a generic NotFound instead of NoSuchKey, which is why the earlier example checks the name. Log the request ID with any error you surface, since AWS support needs it to trace a call.

What changes when migrating from v2?

The v2 end-of-support announcement set September 8, 2025 as the date v2 stopped receiving updates, including fixes for new regions and services. The main changes are mechanical:

v2v3
import AWS from "aws-sdk"import { S3Client } from "@aws-sdk/client-s3"
new AWS.S3().getObject(p).promise()s3.send(new GetObjectCommand(p))
data.Body.toString()await res.Body.transformToString()
AWS.config.update({ region })region per client or AWS_REGION
s3.getSignedUrl("getObject", p)getSignedUrl(s3, cmd) from @aws-sdk/s3-request-presigner
s3.upload() for large filesUpload from @aws-sdk/lib-storage

AWS maintains a codemod, aws-sdk-js-codemod, that rewrites most imports and calls, and the v3 developer guide covers the rest. Global configuration is the part to check by hand, since v3 has no AWS.config and every client has to be configured where it is created.

Which AWS calls can an Encore service drop the SDK for?

Encore

Encore brings infrastructure from code, and the AWS services it provisions have their own APIs in the service code, so most of the SDK calls above go away. A bucket replaces the S3 client, a Pub/Sub topic replaces SNS and SQS, and a database replaces the RDS connection setup, with no client, region or queue URL in the code. On deploy to your AWS account, Encore provisions S3, SNS with SQS and RDS behind them and an IAM role for the service.

Application code passes through Encore and infrastructure guardrails to resources provisioned in your own AWS or GCP account.

The SDK stays for AWS services Encore does not provision, and the two mix in one service. Here a topic delivers receipt jobs, the PDF comes from a bucket, and Amazon SES sends the email through SDK v3:

Set up the app

Get started
brew install encoredev/tap/encore &&
encore app create
Copy

Run in your terminal to get started locally.

~
$ encore app create receipts-api --example=ts/hello-world$ cd receipts-api && npm install @aws-sdk/client-sesv2 && mkdir receipts

Declare the service:

// receipts/encore.service.ts import { Service } from "encore.dev/service"; export default new Service("receipts");

Then the endpoint that sends the receipt:

// receipts/receipts.ts import { api } from "encore.dev/api"; import { Bucket } from "encore.dev/storage/objects"; import { Topic, Subscription } from "encore.dev/pubsub"; import { SESv2Client, SendEmailCommand } from "@aws-sdk/client-sesv2"; const receipts = new Bucket("receipts"); const ses = new SESv2Client({ region: process.env.AWS_REGION ?? "eu-central-1" }); interface ReceiptReady { orderID: string; email: string; } export const receiptReady = new Topic<ReceiptReady>("receipt-ready", { deliveryGuarantee: "at-least-once", }); export const store = api( { expose: false, method: "POST", path: "/receipts" }, async (p: { orderID: string; email: string; pdfBase64: string }): Promise<void> => { await receipts.upload(`${p.orderID}.pdf`, Buffer.from(p.pdfBase64, "base64"), { contentType: "application/pdf", }); await receiptReady.publish({ orderID: p.orderID, email: p.email }); }, ); const _ = new Subscription(receiptReady, "email-receipt", { retryPolicy: { maxRetries: 5 }, handler: async ({ orderID, email }) => { const { url } = await receipts.signedDownloadUrl(`${orderID}.pdf`, { ttl: 7 * 24 * 3600 }); await ses.send( new SendEmailCommand({ FromEmailAddress: "receipts@acme.dev", Destination: { ToAddresses: [email] }, Content: { Simple: { Subject: { Data: `Your receipt for order ${orderID}` }, Body: { Text: { Data: `Download your receipt: ${url}` } }, }, }, }), ); }, });

encore run runs the topic and stores bucket objects on the local filesystem, so the store and publish path works on a laptop, and the SES call uses whatever AWS profile your shell has. In a deployed service the SDK resolves credentials through the same default chain, and the SES permission for that call is granted in AWS, since SES is not an Encore resource. At-least-once delivery means a redelivered message can send a second email, which is why maxRetries is low here, and a sent flag in a database table, checked before calling SES, keeps redeliveries from sending it again.

A coding agent adding a second notification channel works with the topic and bucket APIs in code it can run locally, and only reaches for the SDK when the AWS service has no Encore equivalent.

Best fit: Node.js backends on AWS that want S3, SQS and RDS access without client setup, and still call SES, Textract or other AWS APIs through SDK v3 in the same service.

AWS SDK v3 checklist

  • Install one @aws-sdk/client-* package per service and create clients once at module scope.
  • Rely on the default credential chain, and set the region explicitly.
  • Set connectionTimeout and requestTimeout, and size maxAttempts against the caller's deadline.
  • Use paginators instead of hand-written continuation loops.
  • Catch typed errors such as NoSuchKey, and log $metadata.requestId.
  • Run aws-sdk-js-codemod for v2 code, then review global config by hand.

Frequently asked questions

What is the difference between AWS SDK v2 and v3 for JavaScript?

v3 splits every service into its own package, such as @aws-sdk/client-s3, so you only install and bundle the clients you use, and calls use client.send(new Command(input)) instead of methods with callbacks or .promise(). v2 reached end of support on September 8, 2025 and no longer receives updates.

How does the AWS SDK v3 find credentials in Node.js?

The default provider chain checks environment variables, then SSO and shared config or credentials files, then web identity tokens, then container credentials on ECS and finally the EC2 instance metadata service. On ECS Fargate or Lambda, the task or function role is picked up with no code.

How do I set a timeout on AWS SDK v3 requests?

Pass a NodeHttpHandler from @smithy/node-http-handler as requestHandler with connectionTimeout and requestTimeout in milliseconds, or pass abortSignal: AbortSignal.timeout(ms) as the second argument to send() for a single call. Retries still apply, up to maxAttempts, which defaults to 3.

How do I read an S3 object body as a string in SDK v3?

The GetObjectCommand response Body is a stream with helper methods, so call await res.Body?.transformToString() for text or transformToByteArray() for binary data. For large files, pipe the stream instead of buffering it in memory.

Can an Encore service still use the AWS SDK for APIs Encore does not provision?

Yes. Encore provisions buckets, Pub/Sub topics and databases declared in the service, along with an IAM role for the service, and the AWS SDK stays available in the same service for APIs such as Amazon SES that Encore does not provision.

Deploy to your cloud on AWS and Google Cloud
without managing infrastructure

Encore lets developers and agents define application infrastructure directly in code, then automatically provisions it from local development to production in your AWS or GCP account.

~/orders — claude
Claude Code
Claude Code v2.1.180Opus 5.5~/orders