Connecting and using AWS DynamoDB remotely with NodeJS

Sumant Mishra
3 min readNov 8, 2019

--

In this post, we will discuss how to connect DynamoDB remotely from NodeJS application and perform a few operations like INSERT and GET.

Generally, MongoDB is used with NodeJS if someone thinks about the NoSQL database in his application. But, if the platform is AWS, then people prefer to use AWS DynamoDB service as a NoSQL Database.

In this article, we will discuss how to connect AWS DynamoDB using the aws-sdk npm dependency and implement operations like INSERT and GET. We will also test those APIs using Postman.

Pre-requisites

  • NodeJS and NPM
  • ExpressJS
  • AWS account
  • Access rights to DynamoDB service in AWS

Access rights to DynamoDB is required in the case if the user is an IMA User and not the root user for AWS.

Assuming that you can setup a NodeJS project using ExpressJS framework and define some basic routes like get and post requests.

Let’s get started

Photo by Quino Al on Unsplash

Install aws-sdk NPM package

Here, we will be using aws-sdk npm package to connect to the AWS DynamoDB database. To install aws-sdk npm package, run below command in terminal:

$ npm i aws-sdk --save

Make sure, you have changed your directory to the root directory of your project folder in the terminal.

Store Access and Secret keys in config file

It is required to provide Access key ID and Secret access key for an IAM User while accessing DynamoDB remotely. In case no idea about how to get IAM User credentials, please refer to AWS documentation.

Note: It is not recommended to keep Access key ID and Secret access key in any config file within the source code folder.

Below is the structure of the config file:

[Access key ID] and [Secret access key] need to be replaced with actual Access Key ID and Secret access key.

Coding time

Photo by Joshua Aragon on Unsplash

Here is the code to configure aws-sdk and controller functions:

I would like to highlight a few things in the above code primarily how to use the sdk and DocumentClient of sdk:

  • Import and initialize aws-sdk in your JavaScript code
  • Provide IAM User credentials (Access key ID and Secret access key) by calling config.update method of aws-sdk
  • Initialize DynamoDB.DocumentClient of aws-sdk
  • Call required methods of DocumentClient like (scan or put). DocumentClient methods require parameters like options and callbacks
  • Options require properties like TableName and Item. Item is the record user wants to insert.

I have pushed the source code to:

Hope this helps. If this post is relevant and helpful, please provide your valuable feedback in the comment section.

Thanks!

--

--

Sumant Mishra

Fullstack Architect || TOGAF 9 || AWSCSAA || Cloud Practitioner || NodeJS || React & Angular || Docker || Coder