logo
post image

How to Install and Use AWS Node.js SDK - Getting Started Tutorial

This tutorial discusses installation of AWS Node.js SDK and getting started with it. The following topics are included :

  • Getting AWS Credential Keys
  • Installing AWS Node.js SDK
  • Setting up AWS Credential Keys
  • Writing starter Node.js Code

Step 1 - Getting AWS Credential Keys

  • Login to AWS, and click on the menu My Security Credentials

  • In the next page click on the Access keys tab.

  • Click on the button Create New Access Key, and download the keyfile. Note that the secret key will never be shown in future. If these keys are lost, we need to create new set of keys.

  • The downloaded file will contain AWS Access Key ID & AWS Secret Key. These keys will be required in a later step.

Step 2 - Installing AWS Node.js SDK

  • Create a working directory for our current Node.js app. This directory would contain the AWS SDK and rest of our application files.

  • Open the command line and browse to the created directory (using cd command, or open command line directly from the directory). All commands need to be run from this directory.

    Type in the following command :

    npm init
  • For now, keeping things simple, proceed with the defaults.

    Note that the entry point our app has been set as index.js.

  • Install AWS Node.js SDK with the following command.

    npm install aws-sdk
  • Create 2 files in the directory — index.js & config.json.

    index.js will contain our Node.js code. config.json will hold AWS credential keys.

    The final set of files in the directory should look like the below :

Step 3 - Setting up AWS Credential Keys

Open config.json, and enter the AWS Access Key, Secret Key & AWS region as per the following format. Include the keys that were downloaded before.

{ "accessKeyId": "YOUR-ACCESS-KEY", "secretAccessKey": "YOUR-SECRET-KEY", "region": "us-east-1" }

Step 4 - Writing Stater Node.js Code

  • Open index.js and enter the below code.

    const AWS = require('aws-sdk');
    
    // load AWS credentials
    AWS.config.loadFromPath('./config.json');
    
    // check whether credentials loaded correctly
    AWS.config.getCredentials(function(err) {
    	if(err)
    		console.log(err.stack);
    	else
    		console.log("Access key:", AWS.config.credentials.accessKeyId);
    });
    
    // rest of our application code involving AWS services
    
  • Run our app by executing the below command.

    node index.js
  • If all is correct, the AWS Access Key will be echoed in command line.

Installation is Finished

The above steps will ensure that AWS SDK is correctly set up. Now we can proceed writing further code in index.js using our required AWS services.