How to Configure AWS Credentials in Node

Most common way of configuring AWS credentials in node are

  1. Environment Variable
  2. Load from a JSON file
  3. Updating your configuration

1. Environment Variable

Using environment variables is my preferred way of doing it especially for my npm packages like s3-bucket

All you need to do is add environment variables and then use it while initializing the AWS SDK.

<code class="js">const AWS = require('aws-sdk');

const config = {
    accessKeyId: process.env.AWS_ACCESS_KEY_ID,
    secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY,
    region: process.env.AWS_S3_REGION

let S3 = new AWS.S3(config); //Make sure its let so that you can change later

You might have noticed we generally use environment variables for production apps.

2. Load from a JSON file

Sometimes you might want to just load the credentials from your local JSON file.

In that case, we can use loadFromPath function like this

<code class="json">{
"accessKeyId": "your-access-key",
"secretAccessKey": "your-secret-key",
"region": "your-region"
<code class="js">AWS.config.loadFromPath("./aws_sdk.json");

3. Updating your configuration

There are some use cases in which we need to update our configuration dynamically. In that scenario, we can use update function like this

<code class="js">AWS.config.update({region:'your-region'});