Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use Node js @aws-sdk/client-s3 Using AWS CLI Credentials from .env Only

Nodejs Project with media stored in S3 Bucket and Using @aws-sdk/client-s3 as an AWS SDK Client. .env and S3Bucket.js are as Below.

.env in the Project root directory:

AWS_ACCESSKEYID = AHMXXXXXXXXXXH
AWS_SECRETKEY = fdgggdgdmcxvxcvbvfdgffgfs
AWS_REGION = ap-south-1

Configurations of S3Bucket.js :

const { S3Client, PutObjectCommand, DeleteObjectCommand, HeadObjectCommand } = require('@aws-sdk/client-s3')
const s3 = new S3Client({ accessKeyId: config.AWS_ACCESSKEYID, secretAccessKey: config.AWS_SECRETKEY, signatureVersion: 'v4', region: config.AWS_REGION })

But Still, It is Using the Credentials of local aws credentials, which Means It is using aws-cli creds from ~/.aws/credentials. Instead, It Should use the AWS Credentials from .env Only.

CredentialsProviderError: Could not load credentials from any providers
at  /node_modules/@aws-sdk/credential-provider-node/dist-cjs/defaultProvider.js:13:11
at  /node_modules/@smithy/property-provider/dist-cjs/chain.js:12:39
at processTicksAndRejections (node:internal/process/task_queues:96:5)
at async coalesceProvider ( /node_modules/@smithy/property-provider/dist-cjs/memoize.js:14:24)
at async SignatureV4.credentialProvider ( /node_modules/@smithy/property-provider/dist-cjs/memoize.js:33:24)
at async SignatureV4.signRequest ( /node_modules/@smithy/signature-v4/dist-cjs/SignatureV4.js:106:29)
at async  /node_modules/@aws-sdk/middleware-signing/dist-cjs/awsAuthMiddleware.js:16:18
at async  /node_modules/@smithy/middleware-retry/dist-cjs/retryMiddleware.js:27:46
at async  /node_modules/@aws-sdk/middleware-sdk-s3/dist-cjs/region-redirect-endpoint-middleware.js:14:24
at async  /node_modules/@aws-sdk/middleware-sdk-s3/dist-cjs/region-redirect-middleware.js:9:20 {

I want it to use AWS Credentials from .env and configure this same thing in S3Bucket.js also. but it is fetching creds from ~/.aws/credentials.

like image 781
Ravi Kyada Avatar asked Jun 13 '26 18:06

Ravi Kyada


1 Answers

The way you are supplying credentials is incorrect.

Use the following:

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

const client = new S3Client({
    region: config.AWS_REGION,
    // signatureVersion: 'v4'
    credentials: {
        accessKeyId: config.AWS_ACCESSKEYID,
        secretAccessKey: config.AWS_SECRETKEY
    }
});

I'm not 100% sure that's how you would supply signature v4 on the constructor (the documentation is less than ideal) but I believe that v4 is the default, so you don't need to explicitly set it (and, conceivably, cannot set it).

like image 152
jarmod Avatar answered Jun 16 '26 07:06

jarmod



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!