How To Create a Serverless Node.js App with DynamoDB For The First Time

Aleksandar Simovic
Statuscode
Published in
7 min readOct 19, 2017

The goal of this article will show you how to create a serverless Node.js app with DynamoDB to store and retrieve data. It won’t explain the serverless idea, its benefits and so on, as there are already many articles on serverless covering that.

Serverless is like ice cream. It’s nice to talk about it, but much better to try out.

Because we already mentioned ice creams, the app will be an ice cream shop saving and retrieving ice creams.

First lets see what do you need:

  1. a serverless host — where you’re going to deploy and execute your code and connect to a database. We’re going with AWS, as the most mature platform at the moment.
    AWS has a serverless container service called Lambda. Because Lambda is just a compute service without “outside access”, we also need an “access point” or a “front door” service — AWS API Gateway.
  2. development and deployment tool / library — helps with code setup and deployment. Because serverless is still new and these tools make your life easier. Choosing a library influences the way you build your services. We’re going to use Claudia.js - a development and deployment tool with helpful examples and a good community. It will deploy your service to your AWS serverless container (Lambda) and create an API Gateway for it.
  3. service — your service that receives a request, saves an ice cream to a database or shows all ice creams you saved.
  4. database — a storage to which you connect your service to store ice creams. We’re going with DynamoDB — AWS noSQL database.
The overview of your app infrastructure

1. Serverless host setup — AWS

You need to have an AWS account and a locally set AWS credentials file.
If you already have both setup, scroll to section 2.

If not, open your browser and go to — https://console.aws.amazon.com .

If you don’t have an AWS account, click the “Create a new AWS account” button and follow the process.

If you do, you need only to set your AWS credentials:

  1. Open AWS Console, click on “Services” in the top navigation bar. Write IAM in the search box and click on the resulted IAM.
  2. Click on “Users” on the left side menu, then “Add User”. You will see this.

Type in some user name and check “Programmatic access”. Then click the “Next: Permissions” button.

3. You will be on the 2nd step. Now click the “Attach existing policies directly” and then check “Administrator Full Access”. Proceed to the 3rd step “Review”, and then click the “Create user” for the 4th step.
At the last (4th) step, you will see a table with your user name and columns with your user’s “Access Key Id” and “Secret Access Key Id”. Copy those values.

4. Add those keys to your .aws/credentials file.
a) On OSX/*nix in — ~/.aws
b) On Win its — C:/Users/<your-user>/.aws

[default]
aws_access_key_id = YOUR_ACCESS_KEY
aws_secret_access_key = YOUR_ACCESS_SECRET

Set the AWS_PROFILE environment variable to default .

2. Setup your development and deployment tool — Claudia.js

If you have Claudia.js installed already scroll to section 3.

Open your terminal and run:
npm install -g claudia

Claudia.js is now installed globally, available for all projects.

3. Write your service — Ice Cream Shop

Create your project folder (you can name it ice-cream-shop) and open it in your terminal.

Initialize your Node project.
You can do it quickly by running npm init -f

Then run npm install aws-sdk claudia-api-builder -S
This installs AWS SDK and Claudia API Builder. You need AWS SDK for accessing DynamoDB. Claudia API Builder is a tool for handling routing in your service with an Express-like syntax for your endpoints.

Your service needs to have two endpoints:
1. to save an ice cream — needs a POST request
2. to get all saved ice creams — needs a GET request

Now create an empty index.js file. Open it and type:

You can see that your service included claudia-api-builder and aws-sdk. With Claudia API Builder you exposed two routes:POST /icecreams andGET /icecreams . Using Dynamo DB client methods put and scan you’re adding one or getting all ice creams.

4. Database — setup DynamoDB

Now you need to create a database on AWS. You can do it in two ways:

  • via AWS Console UI
    By going to the AWS Dynamo DB Tables and then clicking on “Create Table” button and then, as on the following picture, supplying icecreams as the table name and icecreamid as the primary key. Click “Create”.
  • via AWS CLI (with one command)
    But before that you need to have AWS CLI installed. For Windows via MSI Installer. For Mac/*nix via Bundled Installer. Follow the steps on the Installer pages. After the installation, just run this:
aws dynamodb create-table --table-name icecreams \
--attribute-definitions AttributeName=icecreamid,AttributeType=S \
--key-schema AttributeName=icecreamid,KeyType=HASH \
--provisioned-throughput ReadCapacityUnits=1,WriteCapacityUnits=1 \
--region us-east-1 \
--query TableDescription.TableArn --output text

This command creates a DynamoDB table named icecreams in the same region as our Lambda, with an key attribute icecreamidof String type. The command returns the table’s Amazon Resource Name (ARN) to confirm that everything is set up correctly.

If you’ve followed properly one those two ways, you should have successfully setup your database. Great!

Giving your service permission for the database

The last step to allow your service access to your DynamoDb database. To do that your service requires a permission policy. Instead of doing it via AWS Console, you can create a policy file in your project and apply it with Claudia.

Inside your ice-cream-shop project folder, create a folder policy and in it a file called dynamodb-policy.json with the following contents:

If copying from here, be sure the code stays in the same spacing. JSON requires proper formatting.

This policy allows your Lambda service to access your DynamoDb database. When invoking Claudia to deploy your code, this policy file location needs to be passed as the deploy option to let Claudia know to assign the policy to your Lambda.

Time for deployment

It’s time for your first deployment. For the first one, Claudia.js needs to create a Lambda for your service. Open the project folder ice-cream-shopand run:

claudia create --region us-east-1 --api-module index --policies policy

This command creates your serverless container (AWS Lambda) in the regionus-east-1, sets the index file as the main service file, and assigns the policy from the policy folder to your Lambda. If successful, returns the created service URL endpoint in the final output, similar to this:

{
"lambda": {
"role": "ice-cream-shop-executor",
"name": "ice-cream-shop",
"region": "us-east-1"
},
"api": {
"id": "your-service-id",
"module": "index",
"url": "https://your-service-url.execute-api.us-east-1.amazonaws.com/latest"
}
}

Trying out your service

You can use cURL for testing. Get all ice creams:

curl https://your-service-url.execute-api.us-east-1.amazonaws.com/latest/icecreams

Save an ice cream:

curl -H "Content-Type: application/json" -X POST -d '{"icecreamId":"123", "name":"chocolate"}' https://your-service-url.execute-api.us-east-1.amazonaws.com/latest/icecreams

By running these commands you’ll see your service working!

That’s it!

Errors?

In case of an error, please check your code if you haven’t missed anything. After an error, invoking the command again may show

'Role with name ice-cream-shop-executor already exists.'

In that case, go to your AWS Console IAM , in the left bar- click “Roles” and find a role with the name error specified and delete it. Then try the previous claudia create command again.

Updating your service

If you want to redeploy to your Lambda with Claudia.js, now you need to do a claudia update instead of create . The full command would look like this:

claudia update

update doesn’t need all those configuration options like create, because Claudia stores them locally for you. If successful, returns the URL of your deployed service.

Now go, you deserve some ice cream! 🍦

The full code example is available in this repository.

If you want to learn more about Serverless with Node.js, take a look at our Serverless Apps with Node.js and Claudia book available for early access by Manning Publications.

Originally posted at Effortless Serverless

--

--

Aleksandar Simovic
Statuscode

Author of "Serverless Applications with Node.js". AWS Serverless Hero. JS Belgrade and Map Meetup Belgrade meetups co-organizer.