AWS SDK V2 to V3 migration with minium code changes in Node JS apis – Javascript

by
Ali Hasan
amazon-web-services aws-aurora-serverless aws-sdk node.js

Quick Fix: Upgrade to AWS SDK for JavaScript V3 and use its API. Refer to the provided links for migration guide and new API reference.

The Problem:

We have an existing Node.js API built using the AWS Serverless Framework that utilizes AWS services through the AWS SDK v2. To enhance our application, we aim to migrate to AWS SDK v3 while minimizing code modifications.

However, during our migration efforts, we encountered a challenge when attempting to continue using v2 commands in v3. Specifically, the response format for the .getObject() method has changed from a buffer in v2 to a ReadableStream in v3. This discrepancy has caused our code to break.

We seek guidance on whether this change in response format is expected when using v2 commands in v3. If so, we would appreciate any insights or best practices on how to handle this efficiently with minimal code changes.

The Solutions:

Solution 1: Migrate to AWS SDK V3 with Minimal Code Changes

Steps:

  1. Upgrade Your Package Manager: Begin by updating your package manager, such as npm or yarn.
  2. Uninstall AWS SDK V2: Execute the following command to remove AWS SDK V2:
    npm uninstall @aws-sdk
    
  3. Install AWS SDK V3: Install AWS SDK V3 using the following command:
    npm install @aws-sdk
    
  4. Import the Required Service: Import the specific AWS service package you need. For example, for S3, use:
    const {S3Client} = require('@aws-sdk/client-s3');
    
  5. Configure the Client: Create a new V3 service client and pass in the necessary configuration values as arguments. For S3, use:
    const s3Client = new S3Client({
      region: 'us-east-1'
    });
    
  6. Use V3 Methods: Use the updated V3 methods to perform API operations. For example, to retrieve an object from S3, use:
    const response = await s3Client.getObject({
      Bucket: 'my-bucket',
      Key: 'my-object'
    });
    
  7. Handle Response: In AWS SDK V3, responses are handled differently. They are now returned as ReadableStreams. To handle the response, use the following code:
    response.Body.pipe(fs.createWriteStream('local-file'));
    

Note:

Q&A

Is it expected that if I want to use v2 commands in v3, I will need code change in the way response is handled?

WHen you upgrade to AWS SDK for JavaScript V3, its a new API. Do not attempt to use V2 calls when you are using V3 API in your project. Refer to the new API Reference to learn the V3 API.

Video Explanation:

The following video, titled "How to assume a role with AWS Security Token Service (STS ...", provides additional insights and in-depth exploration related to the topics discussed in this post.

Play video

... AWS. Whether you use SAML based authentication such as ADFS, OpenID connect, AWS CLI or SDK to access AWS, all of them use AWS STS to obtain ...