Published Nov 6, 2023 ⦁ 7 min read

Leverage AWS Services in Node.js with the JS AWS SDK

Introduction

The JavaScript AWS SDK (also referred to as the JS AWS SDK or AWS SDK for JavaScript) has become an indispensable tool for Node.js developers looking to integrate AWS services into their applications. With its simple API and extensive capabilities, the SDK allows you to easily incorporate virtually any AWS offering like S3, Lambda, DynamoDB, and more into your Node.js code.

Using the JS AWS SDK can provide significant benefits for Node.js developers building on AWS, including increased productivity, reduced boilerplate code, and the ability to leverage the full breadth of AWS services. In this comprehensive guide, we'll provide an in-depth overview of the JS AWS SDK and demonstrate how to perform common operations with code examples for real-world use cases.

Whether you're looking to add AWS capabilities to an existing Node app or build a new serverless application from scratch, read on to see how the flexible and easy-to-use JS AWS SDK can accelerate your development on AWS.

Getting Started with the JS AWS SDK

To use the JS AWS SDK in your Node.js application, you'll first need to install it via npm:

npm install aws-sdk

This will install the core SDK package with support for all AWS services. You can also install individual service packages like aws-sdk-s3 if you only need access to S3.

Once installed, you can reference the AWS SDK in your code:

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

The next step is to initialize the SDK by creating an SDK client object and setting the region and credentials:

const s3 = new AWS.S3({
  region: 'us-east-1', 
  credentials: {
    accessKeyId: 'AKIAIOSFODNN7EXAMPLE',
    secretAccessKey: 'wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY'
  }
});

This creates an S3 client ready to make calls to S3 in the us-east-1 region using the provided access key pair.

Here's a full example making a request to list S3 buckets after initializing the client:

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

const s3 = new AWS.S3({
  region: 'us-east-1',
  credentials: {
    accessKeyId: 'AKIAIOSFODNN7EXAMPLE',
    secretAccessKey: 'wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY'
  }
});

s3.listBuckets(function(err, data) {
  if (err) {
    console.log("Error", err);
  } else {
    console.log("Success", data.Buckets);
  }
});

Authentication

The JS AWS SDK needs credentials to authenticate requests to AWS services. The simplest option is to use an access key pair associated with an IAM user. You can manage users, roles, and credentials from the IAM console.

For security, avoid hardcoding credentials in code. Instead use environment variables or a secure credential file.

Other options like temporary credentials, web identity federation, and SAML support provide more advanced authentication flows for production applications.

Initialization

When creating a service client, you can configure various options like region, endpoint, SSL, retries, and more.

For example:

const dynamodb = new AWS.DynamoDB({
  apiVersion: '2012-08-10',
  region: 'us-west-2',
  httpOptions: {timeout: 1000} 
});

See the SDK documentation for the full set of configuration parameters.

Now let's look at examples using the JS AWS SDK with some key services.

Working with S3 for Storage

Amazon S3 provides highly durable and available object storage that scales massively. The JS AWS SDK makes it easy to integrate S3 into your Node.js applications.

With just a few lines of code, you can perform operations like:

  • Uploading and downloading objects
  • Listing buckets and objects
  • Enabling static website hosting
  • Setting CORS and lifecycle configurations
  • Generating pre-signed URLs for temporary access

For example, to upload a file:

const { S3 } = require('aws-sdk');
const fs = require('fs');

const s3 = new S3();
const fileStream = fs.createReadStream('/file.txt');

const uploadParams = {
  Bucket: 'my-bucket',
  Key: 'object-key',
  Body: fileStream
};

s3.upload(uploadParams, function(err, data) {
  if (err) {
    console.log("Error", err);
  } if (data) {
    console.log("Upload Success", data.Location);  
  }
});

The SDK handles connections, retries, data integrity, security, and more.

Here's an example downloading a file from S3:

const { S3 } = require('aws-sdk');
const fs = require('fs');

const s3 = new S3();

const downloadParams = {
  Bucket: 'my-bucket',
  Key: 'object-key'
};

s3.getObject(downloadParams)
  .createReadStream()
  .pipe(fs.createWriteStream('/tmp/object.txt'))
  .on('error', function(err) {
    console.log('Error downloading file:', err);
  });

And generating a pre-signed URL to share an S3 object:

const { S3 } = require('aws-sdk');

const s3 = new S3();

const params = {
  Bucket: 'my-bucket',
  Key: 'object-key',
  Expires: 60 * 60 // seconds
};

const url = s3.getSignedUrl('getObject', params);

Refer to the S3 Developer Guide for more examples and capabilities.

S3 provides secure, scalable storage for files, websites, analytics, archives, and more. With the JS AWS SDK, you can easily incorporate these capabilities into your Node.js applications.

Building Serverless Apps with Lambda

AWS Lambda provides a serverless compute service that runs your code in response to triggers like HTTP requests. The JS AWS SDK makes it easy to directly invoke Lambda functions from your Node.js applications.

For example, to invoke a function:

const { Lambda } = require('aws-sdk');

const lambda = new Lambda();

const params = {
  FunctionName: 'myFunction',
  Payload: JSON.stringify({
    name: 'John Doe',
  })
};

const result = await lambda.invoke(params).promise();

console.log(result.Payload); // response from function

You can invoke functions synchronously or asynchronously. For async invocations, you can provide a callback to process the response.

Here's an example of building a simple CRUD app with Lambda and DynamoDB:

// Create item in DynamoDB table 
const createResult = await lambda.invoke({
  FunctionName: 'createItemFunction',
  Payload: JSON.stringify({
    id: '123', 
    name: 'Test'
  })
}).promise();

// Get item from DynamoDB
const getResult = await lambda.invoke({
  FunctionName: 'getItemFunction',
  Payload: JSON.stringify({id: '123'})
}).promise();

// Update item in DynamoDB
const updateResult = await lambda.invoke({
  FunctionName: 'updateItemFunction',
  Payload: JSON.stringify({
    id: '123',
    name: 'Test2' 
  })  
}).promise();

// Delete item from DynamoDB
const deleteResult = await lambda.invoke({
  FunctionName: 'deleteItemFunction',
  Payload: JSON.stringify({id: '123'})
}).promise();

Lambda enables event-driven, serverless architectures on AWS. With the JS SDK, you can build full applications using Lambda functions.

Querying Data with DynamoDB

Amazon DynamoDB provides a fully managed NoSQL database service. The JS AWS SDK provides a simple yet powerful API for storing and querying data in DynamoDB from your Node.js apps.

For example, you can perform CRUD operations on items:

const { DynamoDB } = require('aws-sdk');

const docClient = new DynamoDB.DocumentClient(); 

// Write item
const putParams = {
  TableName: 'table',
  Item: {
    primaryKey: 'value',
    otherAttribute: 'value'     
  }
};

await docClient.put(putParams).promise();

// Get item
const getParams = {
  TableName: 'table',
  Key: {
    primaryKey: 'value'
  }
};

const data = await docClient.get(getParams).promise();

// Update item
const updateParams = {
  TableName: 'table',
  Key: {pk: 'value'},
  UpdateExpression: 'set attr1 = :val1',
  ExpressionAttributeValues: {
    ':val1': 'newValue'
  }
};

await docClient.update(updateParams).promise();

// Delete item
const deleteParams = {
  TableName: 'table',
  Key: {pk: 'value'}
};

await docClient.delete(deleteParams).promise();

The DocumentClient provides a high-level API that simplifies interacting with items as JSON documents.

You can also query and scan DynamoDB tables:

// Query items
const queryParams = {
  TableName: 'table',
  KeyConditionExpression: 'pk = :pk',
  ExpressionAttributeValues: {
    ':pk': 'value'
  }
};

const results = await docClient.query(queryParams).promise();

// Scan table 
const scanParams = {
  TableName: 'table'
};

const results = await docClient.scan(scanParams).promise();

DynamoDB offers advanced capabilities like ACID transactions, TTL expiration, atomic counters, streaming, and more. With the DynamoDB SDK, you can leverage these features to build scalable, high-performance apps on AWS.

Conclusion

The JS AWS SDK is an essential tool for Node.js developers looking to build full-stack applications on AWS leveraging services like Lambda, S3, and DynamoDB.

In this comprehensive guide, we covered:

  • Getting started with installing and configuring the SDK
  • Integrating S3 for unlimited, scalable storage
  • Building serverless apps and workflows with Lambda
  • Storing and querying data in DynamoDB tables
  • Real-world code examples for each major service

The SDK handles authentication, retries, edge cases, and other complexities, allowing you to focus on your core app logic. With support for virtually every AWS service, the possibilities are endless for what you can build!

To learn more, be sure to check out the official JS AWS SDK documentation and other Node.js resources on DevHunt. Happy coding!