Next: Working with Services in the SDK for JavaScript, Previous: Loading the SDK for JavaScript, Up: SDK for JavaScript Documentation [Index]
https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/configuring-the-jssdk.html
Before you use the SDK for JavaScript to invoke web services using the API, you must configure the SDK. At a minimum, you must configure these settings:
In addition to these settings, you may also have to configure permissions for your AWS resources. For example, you can limit access to an Amazon S3 bucket or restrict an Amazon DynamoDB table for read-only access.
The topics in this section describe various ways to configure the SDK for JavaScript for Node.js and JavaScript running in a web browser.
https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/global-config-object.html
There are two ways to configure the SDK:
AWS.Config
.
Setting global configuration with AWS.Config
is often easier to get started,
but service-level configuration can provide more control over individual
services. The global configuration specified by AWS.Config
provides default
settings for service objects that you create subsequently, simplifying their
configuration. However, you can update the configuration of individual service
objects when your needs vary from the global configuration.
After you load the aws-sdk
package in your code you can use the AWS global
variable to access the SDK’s classes and interact with individual services.
The SDK includes a global configuration object, AWS.Config
, that you can use to
specify the SDK configuration settings required by your application.
Configure the SDK by setting AWS.Config
properties according to your
application needs. The following table summarizes AWS.Config
properties
commonly used to set the configuration of the SDK.
Configuration Options | Description |
---|---|
credentials | Required. Specifies the credentials used to determine access to services and resources. |
region | Required. Specifies the Region in which requests for services are made. |
maxRetries | Optional. Specifies the maximum number of times a given request is retried. |
logger | Optional. Specifies a logger object to which debugging information is written. |
update | Optional. Updates the current configuration with new values. |
For more information about the configuration object, see Class: AWS.Config in the API Reference.
You must set the Region and the credentials in AWS.Config
. You can set these
properties as part of the AWS.Config
constructor, as shown in the following
browser script example:
var myCredentials = new AWS.CognitoIdentityCredentials({IdentityPoolId:'IDENTITY_POOL_ID'}); var myConfig = new AWS.Config({ credentials: myCredentials, region: 'us-west-2' });
You can also set these properties after creating AWS.Config
using the update
method, as shown in the following example that updates the Region:
myConfig = new AWS.Config(); myConfig.update({region: 'us-east-1'});
You can get your default credentials by calling the static getCredentials()
method of AWS.config
:
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); console.log("Secret access key:", AWS.config.credentials.secretAccessKey); } });
Similarly, if you have set your region correctly in your config file, you get
that value by setting the ‘AWS_SDK_LOAD_CONFIG’ environment variable is set to
a truthy value and calling the static ‘region’ property of AWS.config
:
var AWS = require("aws-sdk"); console.log("Region: ", AWS.config.region);
Each service that you use in the SDK for JavaScript is accessed through a
service object that is part of the API for that service. For example, to
access the Amazon S3 service you create the Amazon S3 service object. You can
specify configuration settings that are specific to a service as part of the
constructor for that service object. When you set configuration values on a
service object, the constructor takes all of the configuration values used by
AWS.Config
, including credentials.
For example, if you need to access Amazon EC2 objects in multiple Regions, create an EC2 service object for each Region and then set the Region configuration of each service object accordingly.
var ec2_regionA = new AWS.EC2({region: 'ap-southeast-2', maxRetries: 15, apiVersion: '2014-10-01'}); var ec2_regionB = new AWS.EC2({region: 'us-east-1', maxRetries: 15, apiVersion: '2014-10-01'});
You can also set configuration values specific to a service when configuring
the SDK with AWS.Config
. The global configuration object supports many
service-specific configuration options. For more information about
service-specific configuration, see Class: AWS.Config in the AWS SDK for
JavaScript API Reference.
Global configuration changes apply to requests for all newly created service objects. Newly created service objects are configured with the current global configuration data first and then any local configuration options. Updates you make to the global AWS.config object don’t apply to previously created service objects.
Existing service objects must be manually updated with new configuration data or you must create and use a new service object that has the new configuration data. The following example creates a new Amazon S3 service object with new configuration data:
s3 = new AWS.S3(s3.config);
https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/setting-region.html
A Region is a named set of AWS resources in the same geographical area. An example of a Region is ‘us-east-1’, which is the US East (N. Virginia) Region. You specify a Region when configuring the SDK for JavaScript so that the SDK accesses the resources in that Region. Some services are available only in specific Regions.
The SDK for JavaScript doesn’t select a Region by default. However, you can set the Region using an environment variable, a shared config file, or the global configuration object.
When you instantiate a service object, you can specify the Region for that resource as part of the client class constructor, as shown here
var s3 = new AWS.S3({apiVersion: '2006-03-01', region: 'us-west-2'});
To set the Region in your JavaScript code, update the AWS.Config
global
configuration object as shown here.
AWS.config.update({region: 'us-east-1'});
You can set the Region using the ‘AWS_REGION’ environment variable. If you define this variable, the SDK for JavaScript reads it and uses it.
Much like the shared credentials file lets you store credentials for use by the
SDK, you can keep your Region and other configuration settings in a shared file
named config
that is used by SDKs. If the ‘AWS_SDK_LOAD_CONFIG’ environment
variable has been set to a truthy value, the SDK for JavaScript automatically
searches for a config
file when it loads. Where you save the config
file
depends on your operating system:
If you don’t already have a shared config
file, you can create one in the
designated directory. In the following example, the config
file sets both
the Region and the output format.
[default] region=us-west-2 output=json
The order of precedence for Region setting is as follows:
https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/specifying-endpoints.html
Calls to API methods in the SDK for JavaScript are made to service endpoint URIs. By default, these endpoints are built from the Region you have configured for your code. However, there are situations in which you need to specify a custom endpoint for your API calls.
https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/getting-your-credentials.html
When you create an AWS account, your account is provided with root credentials. Those credentials consist of two access keys:
For more information on your access keys, see Understanding and Getting Your Security Credentials in the AWS General Reference.
Access keys consist of an access key ID and secret access key, which are used to sign programmatic requests that you make to AWS. If you don’t have access keys, you can create them from the AWS Management Console. As a best practice, do not use the AWS account root user access keys for any task where it’s not required. Instead, create a new administrator IAM user with access keys for yourself.
https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/setting-credentials.html
AWS uses credentials to identify who is calling services and whether access to the requested resources is allowed. In AWS, these credentials are typically the access key ID and the secret access key that were created along with your account.
Whether running in a web browser or in a Node.js server, your JavaScript code
must obtain valid credentials before it can access services through the API.
Credentials can be set globally on the configuration object, using
AWS.Config
, or per service, by passing credentials directly to a service
object.
There are several ways to set credentials that differ between Node.js and JavaScript in web browsers. The topics in this section describe how to set credentials in Node.js or web browsers. In each case, the options are presented in recommended order.
Properly setting credentials ensures that your application or browser script can access the services and resources needed while minimizing exposure to security issues that may impact mission critical applications or compromise sensitive data.
An important principle to apply when setting credentials is to always grant the least privilege required for your task. It’s more secure to provide minimal permissions on your resources and add further permissions as needed, rather than provide permissions that exceed the least privilege and, as a result, be required to fix security issues you might discover later. For example, unless you have a need to read and write individual resources, such as objects in an Amazon S3 bucket or a DynamoDB table, set those permissions to read only.
For more information on granting the least privilege, see the Grant Least Privilege section of the Best Practices topic in the IAM User Guide.
For more information about how to manage your access keys, see Best Practices for Managing AWS Access Keys in the AWS General Reference.
https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/setting-credentials-node.html
There are several ways in Node.js to supply your credentials to the SDK. Some of these are more secure and others afford greater convenience while developing an application. When obtaining credentials in Node.js, be careful about relying on more than one source such as an environment variable and a JSON file you load. You can change the permissions under which your code runs without realizing the change has happened.
Here are the ways you can supply your credentials in order of recommendation:
If more than one credential source is available to the SDK, the default precedence of selection is as follows:
The topics in this section describe how to load credentials into Node.js.
You can keep your AWS credentials data in a shared file used by SDKs and the command line interface.
When the SDK for JavaScript loads, it automatically searches the shared credentials file, which is named "credentials". |
Where you keep the shared credentials file depends on your operating system:
If you do not already have a shared credentials file,
Once you follow those instructions, you should see text similar to the following in the credentials file, where ‘<YOUR_ACCESS_KEY_ID>’ is your access key ID and ‘<YOUR_SECRET_ACCESS_KEY>’ is your secret access key:
[default] aws_access_key_id = <YOUR_ACCESS_KEY_ID> aws_secret_access_key = <YOUR_SECRET_ACCESS_KEY>
The ‘[default]’ section heading specifies a default profile and associated values for credentials. You can create additional profiles in the same shared configuration file, each with its own credential information. The following example shows a configuration file with the default profile and two additional profiles:
[default] ; default profile aws_access_key_id = <DEFAULT_ACCESS_KEY_ID> aws_secret_access_key = <DEFAULT_SECRET_ACCESS_KEY> [personal-account] ; personal account profile aws_access_key_id = <PERSONAL_ACCESS_KEY_ID> aws_secret_access_key = <PERSONAL_SECRET_ACCESS_KEY> [work-account] ; work account profile aws_access_key_id = <WORK_ACCESS_KEY_ID> aws_secret_access_key = <WORK_SECRET_ACCESS_KEY>
By default, the SDK checks the ‘AWS_PROFILE’ environment variable to determine which profile to use. If the ‘AWS_PROFILE’ variable is not set in your environment, the SDK uses the credentials for the ‘[default]’ profile. To use one of the alternate profiles, set or change the value of the ‘AWS_PROFILE’ environment variable. For example, given the configuration file shown above, to use the credentials from the work account, set the ‘AWS_PROFILE’ environment variable to ‘work-account’ (as appropriate for your operating system).
After setting the environment variable (if needed), you can run a file named
script.js
that uses the SDK as follows:
$ node script.js
You can also explicitly select the profile used by the SDK, either by setting
process.env.AWS_PROFILE
before loading the SDK, or by selecting the
credential provider as shown in the following example:
#+cindex:SharedIniFileCredentials var credentials = new AWS.SharedIniFileCredentials({profile: 'work-account'}); AWS.config.credentials = credentials;
The SDK automatically detects AWS credentials set as variables in your environment and uses them for SDK requests, eliminating the need to manage credentials in your application. The environment variables that you set to provide your credentials are:
You can load configuration and credentials from a JSON document on disk using
AWS.config.loadFromPath()
. The path specified is relative to the current
working directory of your process. For example, to load credentials from a
config.json
file with the following content:
{ "accessKeyId": <YOUR_ACCESS_KEY_ID>, "secretAccessKey": <YOUR_SECRET_ACCESS_KEY>, "region": "us-east-1" }
Use the following command:
AWS.config.loadFromPath('./config.json');
Loading credentials from a JSON document is not supported in browser scripts.
You can source credentials by using a method that isn’t built into the SDK. To do this, specify a credential process in the shared AWS config file or the shared credentials file. If the AWS_SDK_LOAD_CONFIG environment variable is set to a truthy value, the SDK will prefer the process specified in the config file over the process specified in the credentials file (if any).
https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/setting-credentials-browser.html
There are several ways to supply your credentials to the SDK from browser scripts. Some of these are more secure and others afford greater convenience while developing a script. Here are the ways you can supply your credentials in order of recommendation:
https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/locking-api-versions.html
https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/node-js-considerations.html
Although Node.js code is JavaScript, using the AWS SDK for JavaScript in Node.js can differ from using the SDK in browser scripts. Some API methods work in Node.js but not in browser scripts, as well as the other way around. And successfully using some APIs depends on your familiarity with common Node.js coding patterns, such as importing and using other Node.js modules like the File System (fs) module.
https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/browser-js-considerations.html
The following topics describe special considerations for using the AWS SDK for JavaScript in browser scripts.
https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/webpack.html
https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/metrics.html
We do not recommend hard coding your AWS credentials in your scripts. Hard coding credentials poses a risk of exposing your access key ID and secret access key.