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
- A user submits a long URL through an HTTP POST request.
- API Gateway forwards the request to AWS Lambda.
- Lambda validates the URL and generates a unique short code.
- The short code and original URL are stored in DynamoDB.
- Lambda returns the shortened URL to the user.
- When someone accesses the shortened URL, API Gateway invokes Lambda again.
- 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 Redirect2. 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:
- Open the AWS Management Console.
- Navigate to Amazon DynamoDB.
- Select Tables and click Create table.
- Enter the following configuration:
Setting | Value |
|---|---|
Table name | URLMappings |
Partition key | shortCode |
Key type | String |
Sort key | Not required |
- Keep the remaining settings at their default values.
- 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.
- Navigate to AWS Lambda.
- Select Create function.
- Choose Author from scratch.
- Enter the following details:
Setting | Value |
|---|---|
Function name | URLShortenerFunction |
Runtime | Node.js 22.x |
Architecture | x86_64 |
Permissions | Create a new execution role |
- Click Create function.
Configure environment variables
Open the Configuration tab and select Environment variables.
Add:
TABLE_NAME = URLMappingsSHORT_BASE_URL = https://your-api-id.execute-api.your-region.amazonaws.comReplace 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-shortenercd url-shortenernpm init -ynpm install @aws-sdk/client-dynamodb @aws-sdk/lib-dynamodbCreate 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.handlerSave 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.
- Open Amazon API Gateway.
- Select Create API.
- Choose HTTP API.
- Click Build.
- Add an integration with
URLShortenerFunction.
- Create the following routes:
HTTP Method | Route | Purpose |
|---|---|---|
POST | /shorten | Generate a shortened URL |
GET | /{shortCode} | Redirect to the original URL |
- Configure both routes to use the same Lambda integration.
- Create a stage and enable automatic deployment.
- Deploy the API.
Copy the generated API endpoint.
For example:
https://abc123.execute-api.ap-south-1.amazonaws.comUpdate the Lambda environment variable:
SHORT_BASE_URL = https://abc123.execute-api.ap-south-1.amazonaws.comMake 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/shortenContent-Type: application/jsonRequest 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/a1b2c3d4e5Lambda 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/invalidcodeExpected 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.
Enjoyed reading this content? Let the author know!
Your likes, comments, shares, and saves help creators reach more builders.
Loading recommendations
Loading article