Skip to content

Aquent | DEV6

Getting Started with DynamoDB using Netlify Functions

Written by: Leonard Lacson

Introduction

Please note that this article assumes prior experience with Netlify Functions. This tutorial does not include the setup process for Netlify Functions, as the focus is getting you setup on using DynamoDB with Netlify Functions. Have a look at this blog to get started with Netlify Functions.

Netlify has helped with making modern web development simpler, through its ever-expanding ecosystem that allows web developers to get their applications built and deployed to production in no time.

One of Netlify’s most popular features are Netlify Functions, which give developers the power to create backend APIs with minimal effort.

Netlify Functions are built on top of AWS Lambda, which simplifies most of the complex setup often associated with Amazon Web Services.

On the other hand, DynamoDB is a NoSQL database service offered by Amazon Web Services. The service is growing in popularity due to its ease-of-use and scalability.

Pre-requisites

Before we dive into this article, please have the following ready:

  • An existing Amazon Web Services account
  • A web application that uses Netlify Functions, deployed on Netlify

If not, feel free to check out the following resources on how to get started:

DynamoDB Endpoints

To connect to DynamoDB, we need to use an endpoint. AWS offers service endpoints, which are a way to programmatically connect to an AWS service such as DynamoDB. This page contains a list of DynamoDB endpoints that we can connect to.

For example, if you were to use the US East (Ohio) or us-east-2 region, the endpoint would be: dynamodb.us-east-2.amazonaws.com.

However, feel free to use a region that applies best to where you are located. Note that you can also use an Amazon VPC (Virtual Private Cloud) endpoint with DynamoDB, which you can learn how to use here.

Creating a Table on DynamoDB

The first step is to  create a table on DynamoDB, using an existing AWS account.

  1. Log into your AWS account. Once you are taken to the AWS Management Console, look for DynamoDB using the Find Services search bar:
Screenshot - AWS management console
  1. You are then taken to the DynamoDB dashboard. Click on the Create table button:
Screenshot - dynamo database dashboard
  1. Add a Table name, and a Primary key. Note that a Primary key is typically a Partition key, with an optional Sort key. Learn more about the different types of primary keys here. For example, we can name a table as “Customers” and add a primary key called “CustomerId”. You can use default table settings for now. Click on Create.
Creating a table in dynamo
  1. Once your table is created, it shows up on your DynamoDB Dashboard, within Tables. Look for your table, and click on the Items tab. On this page, you can create, delete, update, scan, and query for items in your table:
Items tab in dynamo

Setting up Netlify Functions to use DynamoDB

Now that we have a table created on DynamoDB, let’s take a look at how we can connect our functions to that database.

  1. Install aws-sdk and dotenv. aws-sdk is the official AWS SDK for JavaScript, while dotenv allows us to work with a .env file in our application. You can install them by running the following commands:
npm install aws-sdk
npm install dotenv
  1. Create a .env file in the root folder of your application. Add the following lines to it. Make sure to use your own AWS Access Key ID and Secret Access Key for the values of ACCESS_KEY_ID and SECRET_ACCESS_KEY, respectively:
REGION=us-east-2
ENDPOINT=dynamodb.us-east-2.amazonaws.com
ACCESS_KEY_ID=add your AWS access key id here
SECRET_ACCESS_KEY=add your AWS secret access key here
  1. Inside your Netlify Function, add the following lines of code. This ensures that our Netlify Function has access to both the .env file and AWS SDK:
require('dotenv').config();
const AWS = require('aws-sdk');

We configure the AWS SDK to use our account information and chosen endpoint/region (as specified in the .env file) by adding the following:

AWS.config.update({
  region: process.env.REGION,
  endpoint: process.env.ENDPOINT,
  accessKeyId: process.env.ACCESS_KEY_ID,
  secretAccessKey: process.env.SECRET_ACCESS_KEY
});

We then initialize the DynamoDB Document Client. The Document Client simplifies the process of working with DynamoDB items. Without it, we would need to specify attribute values for every DynamoDB item that we use in the function. Learn more about it here.

const db = new AWS.DynamoDB.DocumentClient({region: process.env.REGION });
  1. So far, you should have the following at the beginning of your Netlify Function:
require('dotenv').config();
const AWS = require('aws-sdk');

AWS.config.update({
  region: process.env.REGION,
  endpoint: process.env.ENDPOINT,
  accessKeyId: process.env.ACCESS_KEY_ID,
  secretAccessKey: process.env.SECRET_ACCESS_KEY
});

const db = new AWS.DynamoDB.DocumentClient({ region: process.env.REGION });

// export const handler = async (event) => { ... }

DynamoDB Read and Write operations

Now that we’re done with setting up our Netlify Functions to use DynamoDB, we can look into performing read and write operations. All of these operations are accessed through delegation made by the AWS SDK and DynamoDB’s Document Client. If you would like to know more about working with DynamoDB items and attributes, you can read it here.

1. Creating a new item

In order to create a new item, we would need to use DynamoDB’s PutItem operation. In a Netlify Function, we can do the following:

const createCustomer = () => {
  return db.put({
    TableName: 'Customers',
    Item: {
      CustomerId: '123',
      CustomerName: 'Leonard Lacson'
    },
    ConditionExpression: 'attribute_not_exists(CustomerId)',
  });
}

Let’s break the function down. In the operation, we needed to specify which table to add the item into using TableName. We also had to specify the item’s attributes to be added inside the Item object.

Optionally, we can even provide a ConditionExpression that must be satisfied in order for the PutItem operation to succeed. In our case, we made sure that the CustomerId we are trying to add did not already exist in the database; if it did, then we do not add the item.

You can hit your Netlify Function’s endpoint, and if the API call is successful, you can check out the DynamoDB dashboard for your table to see that a new item has been added.

2. Reading an item

To read an item, we would need to use DynamoDB’s GetItem operation. In a Netlify Function, we can do the following:

const getCustomer = () => {
  return db.get({
    TableName: 'Customers',
    Key: {
      CustomerId: '123'
    },
  });
}

In the snippet above, we are looking for a specific table with TableName and for a customer given a primary key, which in this case is CustomerId.

You can once again hit your Netlify Function’s endpoint, and if the API call is successful, you should be able to get the item that we have created in the previous step.

Note that if there are no matches, GetItem does not return any data and Item will not be included in the response.

You can also check out operations such as Query and Scan on this page.

3. Updating an item

Modifying an existing DynamoDB item can be done through the UpdateItem operation. Use the following in a Netlify Function:

const updateCustomer = () => {
  return db.update({
    TableName: 'Customers',
    Key: {
      CustomerId: '123'
    },
    UpdateExpression: 'set CustomerName = :val',
    ExpressionAttributeValues: {
      ':val': 'Leo'
    },
    ReturnValues: 'UPDATED_NEW'
  });
}

In our code, we specify what kind of update we would like to make using UpdateExpression. In the example, we update the CustomerName using “set”.

We can assign what value to replace the old one with, through the ExpressionAttributeValues. Please note that “:val” can be named anything and is just an easy way to organize expression values.

Lastly, we return only the updated attributes using ReturnValues “UPDATED_NEW”.

You can check your DynamoDB dashboard for any updates made to your database item.

4. Deleting an item

We can delete DynamoDB items using the DeleteItem operation. Let’s take a look:

const deleteCustomer = () => {
  return db.delete({
    TableName: 'Customers',
    Key: {
      CustomerId: '123'
    },
  });
}

Similar to reading an item, we only need the primary key in order to delete an item. However, we can also provide a ConditionExpression similar to creating an item to ensure that we prevent the item from being deleted if the condition is not met.

If your operation is successful, you can check your DynamoDB table to see that the item has been deleted.

Conclusion

As we have learned in this article, Netlify Functions and DynamoDB have both made it easier for developers to get backend services and a database up-and-running, especially on smaller projects. This is great news for new developers or front-end developers looking to transition into back-end or full-stack.

As the Netlify ecosystem continues to evolve, hopefully we also continue to benefit by getting better access to services that not only improve our quality of life as developers, but also open more opportunities to build complex applications with less time, effort, and headaches.

References

Please check out these resources to learn more about DynamoDB and Netlify: