Configuring region in Node.js AWS SDK

Javascriptnode.jsAmazon Web-ServicesAws Sdk

Javascript Problem Overview


Can someone explain how to fix a missing config error with Node.js? I've followed all the examples from the aws doc page but I still get this error no matter what.

{ [ConfigError: Missing region in config]
message: 'Missing region in config',
code: 'ConfigError',
time: Wed Jun 24 2015 21:39:58 GMT-0400 (EDT) }>{ thumbnail: 
 { fieldname: 'thumbnail',
 originalname: 'testDoc.pdf',
 name: 'testDoc.pdf',
 encoding: '7bit',
 mimetype: 'application/pdf',
path: 'uploads/testDoc.pdf',
 extension: 'pdf',
 size: 24,
 truncated: false,
 buffer: null } }
 POST / 200 81.530 ms - -

Here is my code:

var express = require('express');
var router = express.Router();
var AWS = require('aws-sdk');
var dd = new AWS.DynamoDB();
var s3 = new AWS.S3();
var bucketName = 'my-bucket';

AWS.config.update({region:'us-east-1'});

(...)

Javascript Solutions


Solution 1 - Javascript

How about changing the order of statements? Update AWS config before instantiating s3 and dd

var AWS = require('aws-sdk');
AWS.config.update({region:'us-east-1'});

var dd = new AWS.DynamoDB();
var s3 = new AWS.S3();

Solution 2 - Javascript

I had the same issue "Missing region in config" and in my case it was that, unlike in the CLI or Python SDK, the Node SDK won't read from the ~\.aws\config file.

To solve this, you have three options:

  1. Configure it programmatically (hard-coded): AWS.config.update({region:'your-region'});

  2. Use an environment variable. While the CLI uses AWS_DEFAULT_REGION, the Node SDK uses AWS_REGION.

  3. Load from a JSON file using AWS.config.loadFromPath('./config.json');

JSON format:

{ 
    "accessKeyId": "akid", 
    "secretAccessKey": "secret", 
    "region": "us-east-1" 
}

Solution 3 - Javascript

If you work with AWS CLI, you probably have a default region defined in ~/.aws/config. Unfortunately AWS SDK for JavaScript does not load it by default. To load it define env var

AWS_SDK_LOAD_CONFIG=1

See https://github.com/aws/aws-sdk-js/pull/1391

Solution 4 - Javascript

You can specify the region when creating the dynamodb connection (haven't tried s3 but that should work too).

var AWS = require('aws-sdk');
var dd = new AWS.DynamoDB({'region': 'us-east-1'});

Solution 5 - Javascript

Same error for me:

After doing a lot of trials I have settled on the below:

OPTION 1

  1. set the AWS_REGION environment variable in local system only, to us-east-1 (example)

For Linux: > export AWS_ACCESS_KEY_ID=AKIAIOSFODNN7EXAMPLE
> export AWS_SECRET_ACCESS_KEY=wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY
> export AWS_DEFAULT_REGION=us-east-1

For Windows
see: https://docs.aws.amazon.com/cli/latest/userguide/cli-configure-envvars.html

  1. now, no need to set any lambda variables for region

  2. also, no need to use in code, for example:

    • AWS.config.update(...), this is not required
    • AWS.S3(), etc., these will work without any problems. In place of S3, there can be any aws service

In a rare case if somewhere some defaults are assumed in code and you are forced to send region, then use {'region': process.env.AWS_REGION})


OPTION 2

Instead of environment variables, another way is AWS CONFIG file:

On Linux you can create below files:

> ~/.aws/credentials

[default]
aws_access_key_id=AKIAIOSFODNN7EXAMPLE
aws_secret_access_key=wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY

> ~/.aws/config

[default]
region=us-west-2
output=json

See https://docs.aws.amazon.com/cli/latest/userguide/cli-configure-files.html

Solution 6 - Javascript

var AWS = require('aws-sdk');

// assign AWS credentials here in following way:

AWS.config.update({
  accessKeyId: 'asdjsadkskdskskdk',
  secretAccessKey: 'sdsadsissdiidicdsi',
  region: 'us-east-1'
});

var dd = new AWS.DynamoDB();
var s3 = new AWS.S3();

Solution 7 - Javascript

I have gone through your code and here you are connecting to AWS services before setting the region, so i suggest you to update the region first and then connect to services or create instance of those as below -

var express = require('express');
var router = express.Router();
var AWS = require('aws-sdk');
AWS.config.update({region:'us-east-1'});

var dd = new AWS.DynamoDB();
var s3 = new AWS.S3();
var bucketName = 'my-bucket';

Solution 8 - Javascript

I'm impressed this hasn't been posted here yet.

Instead of setting the region with AWS.config.update(), you can use

const s3 = new AWS.S3({
  region: "eu-central-1",
});

to make it instance specific.

Solution 9 - Javascript

This may not be the right way to do it, but I have all my configs in a separate JSON file. And this does fix the issue for me

To load the AWS config, i do this:

var awsConfig = config.aws;
AWS.config.region = awsConfig.region;
AWS.config.credentials = {
	accessKeyId: awsConfig.accessKeyId,
	secretAccessKey: awsConfig.secretAccessKey
}

config.aws is just a JSON file.

Solution 10 - Javascript

To the comment above, you can always it run from your local global config file ~./aws/config by adding the following:

process.env.AWS_SDK_LOAD_CONFIG="true";

This will load your local global config file and use whatever credentials/account you are in which is really handy when iterating through multiple accounts / roles.

Solution 11 - Javascript

You can resolve this issue right in your project directory.

  1. npm i -D dotenv.
  2. Create .env file in root of our project.
  3. Set environment variable AWS_SDK_LOAD_CONFIG=1 in that .env file.
  4. const {config} = require("dotenv"); in the same file where you configure connection to DynamoDB.
  5. config() before you new AWS.DynamoDB().

P.S. As someone have mentioned before, problem is that Node doesn't get data from your aws.config file

Solution 12 - Javascript

You could create a common module and use it based on the region you want to

var AWS = require('aws-sdk')

module.exports = {
    getClient: function(region) {
        AWS.config.update({ region: region })
        return new AWS.S3()
    }
}

and consume it as,

 var s3Client = s3.getClient(config.region)

the idea is to Update AWS config before instantiating s3

Solution 13 - Javascript

I know I am EXTREMELY late to the party, but I have an additional solution which worked for me.

It might be worth passing credentials to each resource directly.

let lambda = AWS.Lambda({region: "us-east-1"});
let credentials = new AWS.SharedIniFileCredentials({
    profile: PROFILE_NAME,   
});

lambda.config.credentials = credentials;

Solution 14 - Javascript

Best Practice would be to utilize an Amazon Cognito Identity pool.

Create an IAM Policy that defines the access to the resource you want. (Least Access Privilege)

Then create an Amazon Cognito Identity Pool allowing unauthenticated identities. Then attached the IAM Policy you created to the Unauthenticated Role for the Identity Pool.

Once that is setup you use the following code:

   AWS.config.region = 'us-east-1';
    AWS.config.credentials = new AWS.CognitoIdentityCredentials({
        IdentityPoolId: 'IdentityPoolIdHere',
    });

Amazon Cognito assumes the IAM Role specified in unauthenticated identities where Amazon STS is utilized in the background which then populates config with temporary credentials with accessibility as defined in the attached IAM Policy for the IAM Role.

Solution 15 - Javascript

var AWS = require("aws-sdk");

AWS.config.getCredentials(function(err) {
  if (err) console.log(err.stack);
  // credentials not loaded
  else {
    console.log("Access key:", AWS.config.credentials.accessKeyId);
  }
});

Solution 16 - Javascript

In my case, I was trying to use it in a React.JS app following this tutorial.

I needed to move the config data to the same file where I was calling the DocumentClient instead of having the config in my index.js file.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAnejah DanielsView Question on Stackoverflow
Solution 1 - JavascriptumbrelView Answer on Stackoverflow
Solution 2 - JavascriptZanonView Answer on Stackoverflow
Solution 3 - JavascriptPeter DotchevView Answer on Stackoverflow
Solution 4 - JavascriptWaffleSouffleView Answer on Stackoverflow
Solution 5 - JavascriptManohar Reddy PoreddyView Answer on Stackoverflow
Solution 6 - JavascriptBHUVNESH KUMARView Answer on Stackoverflow
Solution 7 - JavascriptHimanshu TongyaView Answer on Stackoverflow
Solution 8 - JavascriptSebastianView Answer on Stackoverflow
Solution 9 - JavascriptTonyView Answer on Stackoverflow
Solution 10 - JavascriptRyan CrawfordView Answer on Stackoverflow
Solution 11 - JavascriptEugZView Answer on Stackoverflow
Solution 12 - JavascriptSajeetharanView Answer on Stackoverflow
Solution 13 - JavascriptlachlanvView Answer on Stackoverflow
Solution 14 - JavascriptLeon AfricaView Answer on Stackoverflow
Solution 15 - JavascriptPeters Kings MondayView Answer on Stackoverflow
Solution 16 - JavascriptIanView Answer on Stackoverflow