}) };run();
Path 2 example
Here is a function call in V2 using a promise.
const data = await v2client.command(params).promise()
Here is the V3 version.
const data = await v3client.command(params)
Path 3 examples
The following command installs the AWS Service package for Amazon S3.
npm install @aws-sdk/client-s3;
The following code loads only the Amazon S3 client, reducing the overhead.
import {S3Client, CreateBucketCommand} from '@aws-sdk/client-s3';
If you install only the client of a package, you must also import the V3 commands you want to use.
In this case, the code imports the CreateBucketCommand, which enables you to create an Amazon S3 bucket. You can browse the available commands in your project's node-modules/@aws-sdk/
client-PACKAGE_NAME/commands folder.
The following code creates an Amazon S3 service client object in the us-west-2 Region.
const client = new S3Client({region: 'us-west-2'});
To call imported commands using the recommended async/await pattern, you must import the commands you want to use, and use the following syntax to run the command.
CLIENT.send(newXXXCommand)
The following example creates an Amazon S3 bucket using the async/await pattern, using only the client of the Amazon S3 service package to reduce overhead.
import {S3Client, CreateBucketCommand} from '@aws-sdk/client-s3';
const client = new S3Client({region: 'us-west-2'});
const bucketParams = { Bucket : BUCKET_NAME };
Path 3 examples
(async function () { try{
const data = await client.send(new CreateBucketCommand(bucketParams));
console.log("Success", data);
} catch (err) {
console.log("Error", err);
} })();
For more examples, see SDK for JavaScript code examples (p. 56).
Configuration per service
Configuring the SDK for JavaScript
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:
• The AWS Region in which you will request services
• The credentials that authorize your access to SDK resources
In addition to these settings, you might 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 the ways to configure the SDK for JavaScript for Node.js and JavaScript running in a web browser.
Topics
• Configuration per service (p. 28)
• Setting the AWS Region (p. 29)
• Getting your credentials (p. 30)
• Setting credentials (p. 31)
• Node.js considerations (p. 36)
• Browser Script Considerations (p. 39)
Configuration per service
You can configure the SDK by passing configuration information to a service object.
Service-level configuration provides significant control over individual services, enabling you to update the configuration of individual service objects when your needs vary from the default configuration.
NoteIn version 2.x of the AWS SDK for JavaScript service configuration could be passed to individual client constructors. However, these configurations would first be merged automatically into a copy of the global SDK configuration AWS.config.
Also, calling AWS.config.update({/* params *}) only updated configuration for service clients instantiated after the update call was made, not any existing clients.
This behavior was a frequent source of confusion, and made it difficult to add configuration to the global object that only affects a subset of service clients in a forward-compatible way.
In version 3 , there is no longer a global configuration managed by the SDK. Configuration must be passed to each service client that is instantiated. It is still possible to share the same configuration across multiple clients but that configuration will not be automatically merged with a global state.
Setting configuration per service
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
Setting the AWS Region
object. You can specify configuration settings that are specific to a service as part of the constructor for that service object.
For example, if you need to access Amazon EC2 objects in multiple Regions, create an Amazon EC2 service object for each Region and then set the Region configuration of each service object accordingly.
var ec2_regionA = new EC2({region: 'ap-southeast-2', maxRetries: 15});
var ec2_regionB = new EC2({region: 'us-west-2', maxRetries: 15});
Setting the AWS Region
An AWS 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 creating a service client in the SDK for JavaScript so that the SDK accesses the service 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 AWS Region using an environment variable, or a shared configuration config file.
In a client class constructor
When you instantiate a service object, you can specify the AWS Region for that resource as part of the client class constructor, as shown here.
const s3Client = new S3.S3Client({region: 'us-west-2'});
Using an environment variable
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.
Using a shared config file
Much like the shared credentials file lets you store credentials for use by the SDK, you can keep your AWS Region and other configuration settings in a shared file named config for the SDK to use. If the AWS_SDK_LOAD_CONFIG environment variable is 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:
• Linux, macOS, or Unix users - ~/.aws/config
• Windows users - C:\Users\USER_NAME\.aws\config
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
For more information about using shared config and credentials files, see Loading credentials in Node.js from the shared credentials file (p. 33) or Configuration and credential files in the AWS Command Line Interface User Guide.
Order of precedence for setting the Region
Order of precedence for setting the Region
The following is the order of precedence for Region setting:
1. If a Region is passed to a client class constructor, that Region is used.
2. If a Region is set in the environment variable, that Region is used.
3. Otherwise, the Region defined in the shared config file is used.
Getting your credentials
When you create an AWS account, your account is provided with root credential, or an access key, which consists of the following:
• An access key ID
• A secret access key
For more information about 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.
The only time that you can view or download the secret access key is when you create the keys. You cannot recover them later. However, you can create new access keys at any time. You must also have permissions to perform the required IAM actions. For more information, see Permissions required to access IAM resources in the IAM User Guide.
To create access keys for an IAM user
1. Sign in to the AWS Management Console and open the IAM console at https://
console.aws.amazon.com/iam/.
2. In the navigation pane, choose Users.
3. Choose the name of the user whose access keys you want to create, and then choose the Security credentials tab.
4. In the Access keys section, choose Create access key.
5. To view the new access key pair, choose Show. You will not have access to the secret access key again after this dialog box closes. Your credentials will look something like this:
• Access key ID: AKIAIOSFODNN7EXAMPLE
• Secret access key: wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY
6. To download the key pair, choose Download .csv file. Store the keys in a secure location. You will not have access to the secret access key again after this dialog box closes.
Keep the keys confidential in order to protect your AWS account and never email them. Do not share them outside your organization, even if an inquiry appears to come from AWS or Amazon.com. No one who legitimately represents Amazon will ever ask you for your secret key.
7. After you download the .csv file, choose Close. When you create an access key, the key pair is active by default, and you can use the pair right away.
Related topics
Setting credentials
• What is IAM? in the IAM User Guide
• AWS security credentials in AWS General Reference
Setting credentials
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 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.
Best practices for credentials
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 about granting the least privilege, see the Grant least privilege section of the Best Practices topic in the IAM User Guide.
Warning
While it is possible to do so, we recommend you not hard code credentials inside an application or browser script. Hard coding credentials poses a risk of exposing your access key ID and secret access key.
For more information about how to manage your access keys, see Best practices for managing AWS access keys in the AWS General Reference.
Topics
• Setting credentials in Node.js (p. 31)
• Setting credentials in a web browser (p. 34)
Setting credentials in Node.js
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.
You can supply your credentials in order of recommendation:
Setting credentials in Node.js
1. Loaded from AWS Identity and Access Management (IAM) roles for Amazon EC2 2. Loaded from the shared credentials file (~/.aws/credentials)
3. Loaded from environment variables 4. Loaded from a JSON file on disk
5. Other credential-provider classes provided by the JavaScript SDK
V3 provides a default credential provider in Node.js. So you are not required to supply a credential provider explicitly. The default credential provider attempts to resolve the credentials from a variety of different sources in a given precedence, until a credential is returned from the one of the sources. If the resolved credential is from a dynamic source, which means the credential can expire, the SDK will only use the specific source to refresh the credential.
Here's the order of the sources where the default credential provider resolve credentials from:
1. Environment variables 2. The shared credentials file
3. Credentials loaded from the Amazon ECS credentials provider (if applicable)
4. Credentials loaded from AWS Identity and Access Management using the credentials provider of the Amazon EC2 instance (if configured in the instance metadata)
Warning
We don't recommend hard-coding your AWS credentials in your application. Hard-coding credentials poses a risk of exposing your access key ID and secret access key.
The topics in this section describe how to load credentials into Node.js.
Topics
• Loading credentials in Node.js from IAM roles for Amazon EC2 (p. 32)
• Loading credentials for a Node.js Lambda function (p. 32)
• Loading credentials in Node.js from the shared credentials file (p. 33)
• Loading credentials in Node.js from environment variables (p. 34)
• Loading credentials in Node.js using a configured credential process (p. 34)
Loading credentials in Node.js from IAM roles for Amazon EC2
If you run your Node.js application on an Amazon EC2 instance, you can leverage IAM roles for Amazon EC2 to automatically provide credentials to the instance. If you configure your instance to use IAM roles, the SDK automatically selects the IAM credentials for your application, eliminating the need to manually provide credentials.
For more information about adding IAM roles to an Amazon EC2 instance, see IAM roles for Amazon EC2.
Loading credentials for a Node.js Lambda function
When you create an AWS Lambda function, you must create a special IAM role that has permission to execute the function. This role is called the execution role. When you set up a Lambda function, you must specify the IAM role you created as the corresponding execution role.
The execution role provides the Lambda function with the credentials it needs to run and to invoke other web services. As a result, you don't need to provide credentials to the Node.js code you write within a Lambda function.
Setting credentials in Node.js
For more information about creating a Lambda execution role, see Manage permissions: Using an IAM role (execution role) in the AWS Lambda Developer Guide.
Loading credentials in Node.js from the shared credentials file
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:
• The shared credentials file on Linux, Unix, and macOS: ~/.aws/credentials
• The shared credentials file on Windows: C:\Users\USER_NAME\.aws\credentials
If you do not already have a shared credentials file, see Getting your credentials (p. 30). 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. Create a shared credentials file like below in the directory.
[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, to use the credentials from the work account, set the AWS_PROFILE environment variable to work-account (as appropriate for your operating system).
NoteWhen setting environment variables, be sure to take appropriate actions afterward (according to the needs of your operating system) to make the variables available in the shell or command environment.
After setting the environment variable (if needed), you can run a JavaScreipt file that uses the SDK, such as for example, a file named script.js.
$ node script.js
You can also explicitly select the profile used by a client, as shown in the following example.
const {fromIni} = require("@aws-sdk/credential-provider-ini");
Setting credentials in a web browser
const s3Client = new S3.S3Client({
credentials: fromIni({profile: 'work-account'}) });
Loading credentials in Node.js from environment variables
The SDK automatically detects AWS credentials set as variables in your environment and uses them for SDK requests. This eliminates the need to manage credentials in your application. The environment variables that you set to provide your credentials are:
• AWS_ACCESS_KEY_ID
• AWS_SECRET_ACCESS_KEY
• AWS_SESSION_TOKEN (Optional)
NoteWhen setting environment variables, be sure to take appropriate actions afterward (according to the needs of your operating system) to make the variables available in the shell or command environment.
Loading credentials in Node.js using a configured credential process
For details about specifying a credential process in the shared AWS config file or the shared credentials file, see Sourcing credentials from external processes.
Setting credentials in a web browser
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:
1. Using Amazon Cognito Identity to authenticate users and supply credentials 2. Using web federated identity
3. Hard coding in the script
Warning
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.
Topics
• Using Amazon Cognito Identity to authenticate users (p. 34)
Using Amazon Cognito Identity to authenticate users
The recommended way to obtain AWS credentials for your browser scripts is to use the Amazon Cognito Identity credentials client CognitoIdentityClient. Amazon Cognito enables authentication of users through third-party identity providers.
To use Amazon Cognito Identity, you must first create an identity pool in the Amazon Cognito console.
An identity pool represents the group of identities that your application provides to your users. The
Setting credentials in a web browser
identities given to users uniquely identify each user account. Amazon Cognito identities are not credentials. They are exchanged for credentials using web identity federation support in AWS Security Token Service (AWS STS).
Amazon Cognito helps you manage the abstraction of identities across multiple identity providers. The identity that is loaded is then exchanged for credentials in AWS STS.
Amazon Cognito helps you manage the abstraction of identities across multiple identity providers. The identity that is loaded is then exchanged for credentials in AWS STS.