AWS update credentials in node js sdk v3

Issue

In aws node v2 sdk we can update the credentials after initiating a client

var AWS = require('aws-sdk');
var S3 = AWS.S3();
AWS.config.update({
  accessKeyId: 'AccessKeyId',
  secretAccessKey: 'SecretAccessKey',
  sessionToken: 'SessionToken'
});

Can we update the credentials after initiating the client in v3 sdk

var s3 = require('@aws-sdk/client-s3')
var s3Client = s3.S3Client();
// now update the credentials like in sdk v2

Solution

You can’t update the configuration of a client in v2. If you want to connect to AWS with different credentials, you can simply create another client object:

const { S3Client } = require("@aws-sdk/client-s3");

// client with default credentials from my ./aws/config and ./aws/credentials file
const s3Client = S3Client();

// another client with different credentials
const otherS3Client = new S3Client({
    credentials: {
        accessKeyId: 'AccessKeyId',
        secretAccessKey: 'SecretAccessKey',
        sessionToken: 'SessionToken'
    }
});

In AWS v3 JavaScript SDK the AWS credentials are set per service (see: docs). If you don’t specify any credentials when you create a client, the credential provider will attempt to find your credentials in other places, like environment variables, token cache, etc.

Answered By – Ervin Szilagyi

Answer Checked By – David Marino (AngularFixing Volunteer)

Leave a Reply

Your email address will not be published.