AWS Builder Center

Building a Serverless URL Shortener with AWS Lambda and DynamoDB

Learn how to build a scalable URL shortening service using Amazon API Gateway, AWS Lambda, and DynamoDB. This hands-on tutorial covers API development, URL storage, redirection, deployment, and testing using a fully serverless architecture.

Building a Serverless URL Shortener with AWS Lambda and DynamoDB

Introduction

URL shortening services are widely used in modern applications to convert long URLs into short, shareable links. Instead of maintaining traditional application servers, we can build a lightweight and scalable URL shortener using AWS serverless services.
In this tutorial, we will build a serverless URL shortening application using Amazon API Gateway, AWS Lambda, and Amazon DynamoDB.
The application will allow users to submit a long URL, generate a unique short code, store the mapping in DynamoDB, and redirect users to the original URL whenever they access the shortened link.
By the end of this tutorial, you will understand how these AWS services work together to build a practical serverless application.

1. Architecture Overview

Our application uses three primary AWS services:
  • Amazon API Gateway: Exposes HTTP endpoints to receive URL shortening and redirection requests.
  • AWS Lambda: Executes the application logic without requiring server management.
  • Amazon DynamoDB: Stores the relationship between short codes and original URLs.

Application workflow

  1. A user submits a long URL through an HTTP POST request.
  1. API Gateway forwards the request to AWS Lambda.
  1. Lambda validates the URL and generates a unique short code.
  1. The short code and original URL are stored in DynamoDB.
  1. Lambda returns the shortened URL to the user.
  1. When someone accesses the shortened URL, API Gateway invokes Lambda again.
  1. Lambda retrieves the original URL from DynamoDB and returns an HTTP redirect response.
Architecture diagram:
User / Client
|
|
Amazon API Gateway
|
|
AWS Lambda
/ \
/ \
POST /shorten GET /{shortCode}
| |
| |
Generate Retrieve URL
Short Code |
| |
+------ DynamoDB
|
|
Original URL
|
HTTP 302
Redirect

2. Prerequisites

Before starting, make sure you have:
  • An active AWS account.
  • Basic knowledge of JavaScript and Node.js.
  • Familiarity with REST APIs.
  • Basic understanding of AWS IAM permissions.
  • Node.js installed locally for preparing the deployment package.
We will use Node.js 22 as the Lambda runtime.

3. Create a DynamoDB Table

First, we need a database to store the original URLs and their corresponding short codes.
Follow these steps:
  1. Open the AWS Management Console.
  1. Navigate to Amazon DynamoDB.
  1. Select Tables and click Create table.
  1. Enter the following configuration:
Setting
Value
Table name
URLMappings
Partition key
shortCode
Key type
String
Sort key
Not required
  1. Keep the remaining settings at their default values.
  1. Click Create table.
Our DynamoDB table will store records in the following structure:
{
"shortCode": "a1b2c3d4e5",
"originalUrl": "https://example.com/products/software",
"createdAt": "2026-11-05T12:00:00.000Z"
}
The  shortCode  attribute acts as the partition key, allowing us to retrieve the original URL efficiently.

4. Create the AWS Lambda Function

Next, we will create a Lambda function that handles URL creation and redirection.
  1. Navigate to AWS Lambda.
  1. Select Create function.
  1. Choose Author from scratch.
  1. Enter the following details:
Setting
Value
Function name
URLShortenerFunction
Runtime
Node.js 22.x
Architecture
x86_64
Permissions
Create a new execution role
  1. Click Create function.

Configure environment variables

Open the Configuration tab and select Environment variables.
Add:
TABLE_NAME = URLMappings
SHORT_BASE_URL = https://your-api-id.execute-api.your-region.amazonaws.com
Replace the API URL with your actual API Gateway endpoint after creating the API.

Install dependencies

On your local machine, create a project directory:
mkdir url-shortener
cd url-shortener
npm init -y
npm install @aws-sdk/client-dynamodb @aws-sdk/lib-dynamodb
Create a file named  index.js .

Lambda implementation

The following code handles both URL shortening and redirection using the same Lambda function.
const { DynamoDBClient } = require("@aws-sdk/client-dynamodb");

const {
DynamoDBDocumentClient,
PutCommand,
GetCommand
} = require("@aws-sdk/lib-dynamodb");

const crypto = require("crypto");

const client = new DynamoDBClient({});

const dynamodb = DynamoDBDocumentClient.from(client);

const TABLE_NAME = process.env.TABLE_NAME;
const BASE_URL = process.env.SHORT_BASE_URL;

exports.handler = async (event) => {
try {
const method = event.requestContext.http.method;

// Create a shortened URL
if (method === "POST") {

const body = JSON.parse(event.body || "{}");
const originalUrl = body.longUrl;

if (!originalUrl) {
return {
statusCode: 400,
body: JSON.stringify({
message: "longUrl is required"
})
};
}

let parsedUrl;

try {
parsedUrl = new URL(originalUrl);
} catch {
return {
statusCode: 400,
body: JSON.stringify({
message: "Invalid URL"
})
};
}

if (!["http:", "https:"].includes(parsedUrl.protocol)) {
return {
statusCode: 400,
body: JSON.stringify({
message: "Only HTTP and HTTPS URLs are supported"
})
};
}

const shortCode = crypto
.randomBytes(5)
.toString("hex");

await dynamodb.send(
new PutCommand({
TableName: TABLE_NAME,
Item: {
shortCode,
originalUrl: parsedUrl.toString(),
createdAt: new Date().toISOString()
},
ConditionExpression:
"attribute_not_exists(shortCode)"
})
);

return {
statusCode: 201,
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify({
shortCode,
shortUrl: `${BASE_URL}/${shortCode}`,
originalUrl: parsedUrl.toString()
})
};
}

// Redirect to the original URL
if (method === "GET") {

const shortCode = event.pathParameters?.shortCode;

if (!shortCode) {
return {
statusCode: 400,
body: JSON.stringify({
message: "Short code is required"
})
};
}

const result = await dynamodb.send(
new GetCommand({
TableName: TABLE_NAME,
Key: {
shortCode
}
})
);

if (!result.Item) {
return {
statusCode: 404,
body: JSON.stringify({
message: "Short URL not found"
})
};
}

return {
statusCode: 302,
headers: {
Location: result.Item.originalUrl
},
body: ""
};
}

return {
statusCode: 405,
body: JSON.stringify({
message: "Method not allowed"
})
};

} catch (error) {

console.error("Application error:", error);

return {
statusCode: 500,
body: JSON.stringify({
message: "Internal server error"
})
};
}
};
The implementation uses Node.js's built-in  crypto  module to generate a random ten-character hexadecimal code.
The DynamoDB conditional expression prevents an existing short code from being overwritten if a collision occurs. In a production implementation, you should also implement collision retries.

5. Configure IAM Permissions

Lambda needs permission to read and write records in DynamoDB.
Navigate to:
IAM → Roles → URLShortenerFunction execution role
Attach a custom policy with the following permissions:
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"dynamodb:PutItem",
"dynamodb:GetItem"
],
"Resource": "arn:aws:dynamodb:YOUR_REGION:YOUR_ACCOUNT_ID:table/URLMappings"
}
]
}
Replace  YOUR_REGION  and  YOUR_ACCOUNT_ID  with your actual AWS values.
This follows the principle of least privilege by allowing only the required DynamoDB operations on the specified table.

6. Deploy the Lambda Function

Because our function uses external AWS SDK packages, we need to include the dependencies in the deployment package.
From the project directory, create a ZIP archive containing:
  • index.js
  • package.json
  • package-lock.json
  • node_modules/
Upload the ZIP file through:
AWS Lambda → URLShortenerFunction → Upload from → .zip file
Set the handler to:
index.handler
Save the changes and verify that the deployment completes successfully.

7. Create an API Using Amazon API Gateway

Now we need HTTP endpoints that allow users to interact with our Lambda function.
  1. Open Amazon API Gateway.
  1. Select Create API.
  1. Choose HTTP API.
  1. Click Build.
  1. Add an integration with  URLShortenerFunction .
  1. Create the following routes:
HTTP Method
Route
Purpose
POST
/shorten
Generate a shortened URL
GET
/{shortCode}
Redirect to the original URL
  1. Configure both routes to use the same Lambda integration.
  1. Create a stage and enable automatic deployment.
  1. Deploy the API.
Copy the generated API endpoint.
For example:
https://abc123.execute-api.ap-south-1.amazonaws.com
Update the Lambda environment variable:
SHORT_BASE_URL = https://abc123.execute-api.ap-south-1.amazonaws.com
Make sure the API routes and Lambda proxy integration are configured correctly.

8. Test the Application

Our serverless URL shortener is now ready for testing.
We can use Postman or curl to test the endpoints.

Test 1: Generate a shortened URL

Send a POST request:
POST https://abc123.execute-api.ap-south-1.amazonaws.com/shorten
Content-Type: application/json
Request body:
{
"longUrl": "https://aws.amazon.com/lambda/"
}
Expected response:
{
"shortCode": "a1b2c3d4e5",
"shortUrl": "https://abc123.execute-api.ap-south-1.amazonaws.com/a1b2c3d4e5",
"originalUrl": "https://aws.amazon.com/lambda/"
}

Test 2: Redirect to the original URL

Open the generated shortened URL in a browser:
https://abc123.execute-api.ap-south-1.amazonaws.com/a1b2c3d4e5
Lambda retrieves the corresponding record from DynamoDB and returns an HTTP 302 redirect.
The browser then navigates to the original destination.

Test 3: Handle invalid short codes

Try accessing a short code that does not exist:
https://abc123.execute-api.ap-south-1.amazonaws.com/invalidcode
Expected response:
{
"message": "Short URL not found"
}
The application returns an HTTP 404 response.

9. Security and Optimization Considerations

For a production-ready implementation, consider the following improvements:
1. API throttling
Configure throttling in API Gateway to reduce excessive requests and protect the application from abuse.
2. Input validation
Validate submitted URLs and reject unsupported protocols. Apply request size limits and additional abuse protection.
3. IAM security
Use narrowly scoped IAM permissions rather than granting unrestricted DynamoDB access.
4. Monitoring
Use Amazon CloudWatch Logs and CloudWatch Metrics to monitor Lambda invocations, errors, latency, and API activity.
5. URL expiration
Implement DynamoDB Time to Live (TTL) if shortened URLs should expire automatically.
6. Collision handling
Implement retry logic when a generated short code already exists.
7. Authentication and rate limiting
For applications with public access, consider Amazon Cognito authentication, API throttling, and abuse detection.

10. Conclusion

In this tutorial, we built a serverless URL shortening application using Amazon API Gateway, AWS Lambda, and Amazon DynamoDB.
We learned how to:
  • Create a DynamoDB table to store URL mappings.
  • Develop a Lambda function using Node.js.
  • Configure IAM permissions for secure database access.
  • Expose RESTful HTTP endpoints through API Gateway.
  • Generate short URLs and redirect users to their original destinations.
  • Test the application using HTTP requests.
The biggest advantage of this architecture is that we do not need to provision or maintain traditional application servers. AWS manages the underlying infrastructure, allowing developers to focus on application logic.
This project demonstrates how multiple AWS managed services can work together to build a lightweight, scalable, and cost-conscious serverless application.
What's Next?
Try extending this application by adding click analytics, custom aliases, URL expiration, authentication, and a dashboard to monitor URL usage.
Building small applications like this is an effective way to understand cloud architecture and gain practical experience with AWS services.


Disclaimer: This tutorial is an educational implementation. Test the application in your own AWS account, review applicable service pricing, and apply production security controls before exposing it publicly.
Any opinions in this article are those of the individual author and may not reflect the opinions of AWS.
Enjoyed reading this content? Let the author know!

Your likes, comments, shares, and saves help creators reach more builders.

Loading recommendations

Loading article