Guide
@aws-sdk v3 vs v2 Migration Guide 2026



Complete guide to migrating from AWS SDK v2 to v3 in 2026. Modular clients, middleware stack, tree-shaking, TypeScript improvements, and bundle size impact.
Contents
Contents
TL;DR
Use AWS SDK for JavaScript v3 for new projects and migrate existing aws-sdk imports. AWS ended support for v2 on September 8, 2025, so it no longer receives updates or security fixes. With v3, install the clients for the services you use, send commands through those clients, and update any pagination loops.
Key Takeaways
- Modular clients. Install
@aws-sdk/client-s3if your function only calls S3. - Bundle size. Measure the packaged function after the switch. Installed dependency size and deployed bytes measure different things.
- Middleware. Add request logging or other cross-cutting behavior through the middleware stack.
- TypeScript. Check your inputs and outputs against the types for each command.
- Pagination. Start with a list call and confirm that it returns results beyond the first page.
Where to Look for v2
Check application imports and the lockfile for aws-sdk. If it remains after you migrate your direct imports, identify the dependency that still pulls it in. Check older Lambda functions for imports that expect the runtime to supply aws-sdk. Lambda switched its included SDK from v2 to v3 with Node.js 18.
Architecture Differences
v2: Single Monolithic Package
// v2: one import, everything available
import AWS from 'aws-sdk'
// Instantiate any service
const s3 = new AWS.S3({ region: 'us-east-1' })
const dynamodb = new AWS.DynamoDB({ region: 'us-east-1' })
const lambda = new AWS.Lambda({ region: 'us-east-1' })
The aws-sdk package covers all AWS services. An S3-only function can switch to the dedicated S3 package.
v3: Modular Service Packages
// v3: import only what you need
import { S3Client, GetObjectCommand, PutObjectCommand } from '@aws-sdk/client-s3'
import { DynamoDBClient, GetItemCommand } from '@aws-sdk/client-dynamodb'
const s3 = new S3Client({ region: 'us-east-1' })
const ddb = new DynamoDBClient({ region: 'us-east-1' })
The v3 SDK publishes separate service clients. Use the S3 client for S3 calls and add the DynamoDB client only where the application needs it.
Migration: Common Patterns
S3
// ===== v2 =====
import AWS from 'aws-sdk'
const s3 = new AWS.S3()
// Get object
const result = await s3.getObject({
Bucket: 'my-bucket',
Key: 'my-key',
}).promise()
const body = result.Body?.toString()
// Put object
await s3.putObject({
Bucket: 'my-bucket',
Key: 'my-key',
Body: 'hello world',
ContentType: 'text/plain',
}).promise()
// ===== v3 =====
import { S3Client, GetObjectCommand, PutObjectCommand } from '@aws-sdk/client-s3'
import { getSignedUrl } from '@aws-sdk/s3-request-presigner'
const s3 = new S3Client({ region: 'us-east-1' })
// Get object
const result = await s3.send(new GetObjectCommand({
Bucket: 'my-bucket',
Key: 'my-key',
}))
// Body is now a ReadableStream — convert appropriately:
const body = await result.Body?.transformToString()
// Put object
await s3.send(new PutObjectCommand({
Bucket: 'my-bucket',
Key: 'my-key',
Body: 'hello world',
ContentType: 'text/plain',
}))
// Presigned URL (separate package in v3)
const url = await getSignedUrl(s3, new GetObjectCommand({
Bucket: 'my-bucket',
Key: 'my-key',
}), { expiresIn: 3600 })
The key v3 changes for S3:
.promise()is gone — all operations return Promises nativelyBodyis aReadableStream | Blob | string, not aBuffer— use.transformToString(),.transformToByteArray(), or pipe it- Presigned URLs require
@aws-sdk/s3-request-presigneras a separate install
DynamoDB
// ===== v2 =====
const docClient = new AWS.DynamoDB.DocumentClient()
const result = await docClient.get({
TableName: 'Users',
Key: { userId: '123' },
}).promise()
const user = result.Item
// ===== v3: DynamoDB DocumentClient =====
import { DynamoDBClient } from '@aws-sdk/client-dynamodb'
import { DynamoDBDocumentClient, GetCommand, PutCommand, QueryCommand } from '@aws-sdk/lib-dynamodb'
const client = new DynamoDBClient({ region: 'us-east-1' })
const docClient = DynamoDBDocumentClient.from(client, {
marshallOptions: { removeUndefinedValues: true },
})
// Get
const result = await docClient.send(new GetCommand({
TableName: 'Users',
Key: { userId: '123' },
}))
const user = result.Item // typed, no manual unmarshalling
// Put
await docClient.send(new PutCommand({
TableName: 'Users',
Item: { userId: '123', name: 'Alice', createdAt: new Date().toISOString() },
}))
// Query with expression
const queryResult = await docClient.send(new QueryCommand({
TableName: 'Users',
IndexName: 'email-index',
KeyConditionExpression: 'email = :email',
ExpressionAttributeValues: { ':email': 'alice@example.com' },
}))
const users = queryResult.Items ?? []
The @aws-sdk/lib-dynamodb package provides the DocumentClient equivalent — it handles marshalling/unmarshalling JavaScript values to DynamoDB's typed format. Install it alongside @aws-sdk/client-dynamodb.
SES (Email)
// v2
await ses.sendEmail({
Source: 'noreply@example.com',
Destination: { ToAddresses: ['user@example.com'] },
Message: {
Subject: { Data: 'Hello' },
Body: { Text: { Data: 'World' } },
},
}).promise()
// v3 — use SESv2 for new features (templates, contacts)
import { SESv2Client, SendEmailCommand } from '@aws-sdk/client-sesv2'
const ses = new SESv2Client({ region: 'us-east-1' })
await ses.send(new SendEmailCommand({
FromEmailAddress: 'noreply@example.com',
Destination: { ToAddresses: ['user@example.com'] },
Content: {
Simple: {
Subject: { Data: 'Hello' },
Body: { Text: { Data: 'World' } },
},
},
}))
Pagination: The Biggest API Improvement
For S3's ListObjectsV2 operation, paginateListObjectsV2 handles continuation tokens for you.
// ===== v2: manual pagination =====
let continuationToken: string | undefined
const allObjects: AWS.S3.Object[] = []
do {
const result = await s3.listObjectsV2({
Bucket: 'my-bucket',
ContinuationToken: continuationToken,
}).promise()
allObjects.push(...(result.Contents ?? []))
continuationToken = result.NextContinuationToken
} while (continuationToken)
// ===== v3: built-in paginator =====
import { S3Client, paginateListObjectsV2 } from '@aws-sdk/client-s3'
const s3 = new S3Client({ region: 'us-east-1' })
const allObjects = []
for await (const page of paginateListObjectsV2({ client: s3 }, { Bucket: 'my-bucket' })) {
allObjects.push(...(page.Contents ?? []))
}
// Automatic pagination — no token management needed
Test the paginator with enough objects to return more than one page before removing the old loop.
Middleware Stack
v3's middleware system is the most powerful architectural improvement:
import { S3Client } from '@aws-sdk/client-s3'
const s3 = new S3Client({ region: 'us-east-1' })
// Add logging middleware
s3.middlewareStack.add(
(next, context) => async (args) => {
console.log(`[AWS] ${context.commandName} started`)
const start = Date.now()
const result = await next(args)
console.log(`[AWS] ${context.commandName} completed in ${Date.now() - start}ms`)
return result
},
{
step: 'initialize',
name: 'loggingMiddleware',
}
)
// Add custom retry logic middleware
s3.middlewareStack.add(
(next) => async (args) => {
let attempt = 0
while (true) {
try {
return await next(args)
} catch (err) {
if (attempt++ >= 3) throw err
await new Promise(resolve => setTimeout(resolve, 2 ** attempt * 100))
}
}
},
{ step: 'finalizeRequest', name: 'retryMiddleware' }
)
The middleware stack replaces v2's event hooks with a composable, typed system. Libraries can export middleware plugins that users opt into.
TypeScript Improvements
v3 generates TypeScript types directly from AWS service API definitions:
import { PutItemCommandInput } from '@aws-sdk/client-dynamodb'
// ✅ Fully typed — TypeScript knows all valid fields and their types
const input: PutItemCommandInput = {
TableName: 'Users',
Item: {
userId: { S: '123' }, // 'S' for string
count: { N: '42' }, // 'N' for number (as string)
active: { BOOL: true }, // 'BOOL' for boolean
},
ConditionExpression: 'attribute_not_exists(userId)',
}
In v2, most inputs and outputs were typed as any or with loose types. v3 gives precise types per operation, including response shapes — enabling autocompletion and catching type errors at compile time.
Bundle Size Impact
Compare deployment artifacts from the same function before and after migration. Pin the SDK and bundler versions and use the same Node.js target and build settings. Record installed dependency bytes and ZIP bytes separately. If you rely on Lambda's runtime-included SDK, note that choice alongside any packaged build.
Error Handling
v3 improves error handling with typed error classes per service:
import { S3Client, GetObjectCommand } from '@aws-sdk/client-s3'
import { NoSuchKey, S3ServiceException } from '@aws-sdk/client-s3'
const s3 = new S3Client({ region: 'us-east-1' })
try {
const result = await s3.send(new GetObjectCommand({
Bucket: 'my-bucket',
Key: 'missing-file.txt',
}))
} catch (err) {
if (err instanceof NoSuchKey) {
// Typed: this is specifically a 404 NoSuchKey error
console.log('File does not exist')
} else if (err instanceof S3ServiceException) {
// Any other S3 service error
console.log(`S3 error: ${err.name} — ${err.message}`)
console.log(`HTTP status: ${err.$response?.statusCode}`)
} else {
// Network error, timeout, etc.
throw err
}
}
In v2, error handling required checking err.code string values (err.code === 'NoSuchKey'). v3 gives you instanceof checks with TypeScript-aware typed error classes, one per AWS error code.
Credentials Configuration
// v3 credential providers
import { S3Client } from '@aws-sdk/client-s3'
import { fromEnv } from '@aws-sdk/credential-providers'
import { fromIni } from '@aws-sdk/credential-providers'
import { fromTemporaryCredentials } from '@aws-sdk/credential-providers'
// Explicit env vars
const s3 = new S3Client({
region: 'us-east-1',
credentials: fromEnv(), // AWS_ACCESS_KEY_ID + AWS_SECRET_ACCESS_KEY
})
// Assume a role (common in CI and cross-account access)
const crossAccountS3 = new S3Client({
region: 'us-east-1',
credentials: fromTemporaryCredentials({
params: {
RoleArn: 'arn:aws:iam::123456789:role/MyRole',
RoleSessionName: 'my-session',
},
}),
})
// Named profile from ~/.aws/credentials
const profileS3 = new S3Client({
region: 'us-east-1',
credentials: fromIni({ profile: 'staging' }),
})
The @aws-sdk/credential-providers package consolidates all credential sources — environment variables, IAM roles, SSO, web identity tokens, and more. The default credential chain (no credentials option) checks environment → ECS task role → EC2 instance metadata, which works for most production deployments.
Ecosystem & Community
The @aws-sdk v3 package family is one of the most actively maintained open-source projects in the JavaScript ecosystem. The AWS SDK JavaScript team at Amazon releases updates weekly, with service-specific packages tracking the AWS API changelog. The monorepo at github.com/aws/aws-sdk-js-v3 has 3,000+ contributors and is the source of truth for v3 development.
The community around AWS SDK v3 includes several high-quality third-party utilities. aws-lite provides a lightweight alternative client for teams that find v3 too heavy for specific use cases. Serverless Framework and AWS CDK both use v3 internally. The SST (Serverless Stack) framework, popular for full-stack serverless applications, builds its resource bindings on top of v3 clients. The @smithy/* packages that underpin v3's architecture are themselves useful for teams building non-AWS AWS-compatible APIs (like MinIO or Localstack wrappers).
For local development, LocalStack provides a Docker-based mock of AWS services that works seamlessly with v3 clients. The @aws-sdk/credential-providers's fromEnv() provider is commonly used in conjunction with LocalStack for local development without real AWS credentials.
Real-World Adoption
The middleware system has enabled a new category of AWS SDK extensions. Datadog's AWS Lambda integration, OpenTelemetry tracing for AWS, and custom retry/circuit-breaker implementations all use v3's middleware API. These would have required SDK forks or monkey-patching in v2.
Teams report that the v3 TypeScript improvements alone often justify the migration. Catching incorrect DynamoDB expression attribute value formats at compile time — rather than getting a runtime error from AWS — saves debugging time in production environments where AWS API errors can be slow to reproduce.
Developer Experience Deep Dive
The Command pattern in v3 (client.send(new GetObjectCommand(...))) is more verbose than v2's method-on-client approach (s3.getObject(...).promise()). This verbosity is intentional — it makes the operation explicit and enables TypeScript to provide precise types for each command's input and output. Once you're used to it, autocomplete on Command classes is significantly better than v2's loose typing.
The separate package architecture does add cognitive overhead during setup. For a Lambda that uses S3, SES, and DynamoDB, you install three separate packages (@aws-sdk/client-s3, @aws-sdk/client-sesv2, @aws-sdk/client-dynamodb) plus @aws-sdk/lib-dynamodb for the DocumentClient equivalent. The npm install command is longer, but the resulting bundle is dramatically smaller.
Documentation quality for v3 is excellent. The AWS Developer Guide provides service-specific examples for v3, and the TypeScript types themselves are auto-generated documentation — hovering over a command in VS Code shows the full API reference inline. The migration documentation at docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide is comprehensive.
The local development story with LocalStack and v3 is smooth. You configure a custom endpoint URL and the credential provider uses test credentials, making it possible to develop AWS-integrated code without incurring AWS costs or requiring network access.
Performance & Lambda Optimization
If cold starts matter for the function you are migrating, compare Lambda initialization duration in milliseconds before and after the switch. Use the same runtime, memory setting, region and event payload for both versions.
Beyond bundle size, v3's connection reuse is configurable at the client level. By default, v3 clients reuse HTTP connections within a Lambda execution environment. For high-throughput functions making many API calls, configuring the max connections via requestHandler configuration prevents connection exhaustion.
Keeping AWS clients as module-level singletons (not re-instantiating them per Lambda invocation) is a critical optimization that applies to both v2 and v3. Module-level clients are re-used across warm Lambda invocations, avoiding the overhead of re-establishing connections and re-discovering credentials.
// Correct: module-level singleton
const s3 = new S3Client({ region: process.env.AWS_REGION })
export async function handler(event: APIGatewayEvent) {
// Uses the same s3 client on warm invocations
const result = await s3.send(new GetObjectCommand({ ... }))
}
For Bun and Deno runtimes (increasingly common for serverless workloads), v3's native ES module support is essential — both runtimes have limited or no support for CommonJS, and v3's ESM-first design ensures compatibility.
Migration Checklist
When migrating a project from v2 to v3:
[ ] Replace aws-sdk with individual @aws-sdk/client-* packages
[ ] Update all instantiation: new AWS.S3() → new S3Client()
[ ] Remove .promise() calls — v3 returns Promises natively
[ ] Update S3 Body handling: Buffer → transformToString() / transformToByteArray()
[ ] Install @aws-sdk/lib-dynamodb for DocumentClient equivalent
[ ] Replace manual pagination loops with paginate* helpers
[ ] Update presigned URL code to @aws-sdk/s3-request-presigner
[ ] Update credential configuration (CredentialProvider changed)
[ ] Test the deployment artifact on your supported Lambda Node.js runtime
[ ] Enable bundling (esbuild/tsup) for Lambda to get tree-shaking benefits
Final Verdict 2026
Use AWS SDK for JavaScript v3 on new projects. For an existing application, migrate one service client at a time. Run its integration tests and confirm pagination, credentials and response handling before removing aws-sdk.
Methodology
Use the service examples as migration patterns. Run the migration checklist against the actual artifact and the Lambda runtime you deploy to.
Source notes
- Check the end-of-support date and migration steps in the AWS SDK v2 reference and the AWS SDK v3 migration guide.
- Check the Node.js 18 runtime announcement for the switch to v3 and the Lambda runtime SDK reference for what Lambda includes today.
- For the pagination example, see AWS's
ListObjectsV2example.
Compare AWS SDK with other cloud SDKs on PkgPulse.
See also: AWS courses and tutorials on CourseFacts — learn AWS SDK, serverless, and cloud infrastructure from top-rated courses.
Testing Strategies for AWS SDK v3 Code
Testing code that calls AWS services presents consistent challenges: real AWS calls cost money, require network access, and make tests slow and non-deterministic. AWS SDK v3's architecture makes several testing strategies practical.
The most common approach is mocking with @aws-sdk/client-s3's or any service client's mockClient utility from the aws-sdk-client-mock package. This package intercepts client.send() calls at the middleware level and returns configured mock responses:
The middleware stack is the key enabler here. By intercepting at the send() level, you mock the entire AWS HTTP request/response cycle without any network access. Your test asserts that PutObjectCommand was called with specific parameters, and the mock returns the exact response shape your code expects.
For local development and integration tests, LocalStack provides a Docker container that implements most AWS service APIs locally. v3 clients work seamlessly with LocalStack by setting a custom endpoint in the client configuration pointing to http://localhost:4566. This approach is more realistic than unit mocks for testing DynamoDB queries and S3 bucket policies.
Serverless and Lambda Best Practices
AWS SDK v3 was designed with serverless workloads in mind, and several patterns significantly affect Lambda performance. The most important: instantiate AWS clients outside your handler function, at the module level. Lambda execution environments are reused across warm invocations, meaning module-level code runs once while the handler runs on every request. A DynamoDB client created inside the handler re-establishes its configuration and credentials on every invocation — expensive and unnecessary.
Connection pooling in v3 is handled by the NodeHttpHandler from @aws-sdk/node-http-handler. For Lambda functions making many concurrent AWS API calls, configuring maxSockets prevents connection pool exhaustion under load. The default is 50 concurrent connections per client, which is appropriate for most functions but may need tuning for high-concurrency workloads.
Supported Lambda Node.js runtimes include a runtime-specific minor version of AWS SDK for JavaScript v3. Bundle the SDK clients you use when you need the deployed SDK version to match your lockfile. If you externalize a client, test with the runtime-provided version for your runtime and AWS Region.
Working with S3 Presigned URLs
Presigned URLs are one of the most common S3 patterns — generate a URL that grants temporary access to a private object, or allows a client to upload directly to S3 without exposing credentials. v3 handles this via the @aws-sdk/s3-request-presigner package (separate from @aws-sdk/client-s3).
Presigned POST URLs (for browser uploads) use a different package: @aws-sdk/s3-presigned-post. The distinction matters because presigned PUT vs presigned POST have different security and size constraint capabilities. Presigned PUT is simpler and works with fetch. Presigned POST supports server-side size limits and content-type restrictions enforced by S3, making it the right choice for user-generated content uploads where you want to prevent oversized file uploads.
Both approaches eliminate the need to route file data through your server — the client uploads directly to S3, which scales independently of your API server.
v3 in the Broader AWS Ecosystem
The move to v3 aligns with the broader direction of AWS infrastructure tooling for JavaScript. AWS CDK v2, the infrastructure-as-code framework, uses v3 internally. SST v3 (Serverless Stack), one of the most popular full-stack serverless frameworks, builds on v3 clients for its resource bindings. Architect (arc.codes) has v3 support. The tooling ecosystem has essentially completed the v3 transition — new libraries and frameworks in the AWS/serverless JavaScript space don't support v2.
For teams building event-driven architectures alongside their REST APIs, understanding EventBridge, SQS, and SNS with v3 follows the same modular pattern: @aws-sdk/client-eventbridge, @aws-sdk/client-sqs, @aws-sdk/client-sns. Each service has dedicated paginators, typed error classes, and middleware support. The migration checklist from the main section of this guide applies to all services.
For database alternatives that work alongside AWS architectures — particularly for applications that want more SQL expressiveness than DynamoDB — see the comparison of Neon vs Supabase vs Tembo serverless Postgres for serverless-native Postgres options that integrate cleanly with Lambda functions.
Vendor Lock-in Considerations
A reasonable concern when adopting v3 deeply is vendor lock-in. AWS SDK v3 is AWS-specific — it doesn't abstract over cloud providers. If there's a chance your application needs to run on GCP or Azure in the future, AWS SDK v3 calls are not portable.
Practically, most teams don't switch cloud providers after choosing AWS, and abstracting over cloud providers adds significant complexity for uncertain benefit. The pragmatic approach is to isolate AWS SDK calls behind repository or service interfaces in your application code. This provides the benefit of testability (mock the interface, not the SDK) and makes the surface area of AWS-specific code visible. If you ever need to swap S3 for GCP Cloud Storage, the change is contained to the repository implementation.
For infrastructure decisions like CI/CD, secrets management, and database selection that complement your AWS usage, see the 20 fastest growing npm packages 2026 for emerging tooling that pairs well with modern AWS deployments.
Related: Best Email Libraries Node.js 2026 for SES alternatives, Best WebSocket Libraries Node.js 2026 for real-time features alongside your AWS backend, and Turso vs PlanetScale vs Neon serverless database 2026 for database alternatives to DynamoDB.