Building and Deploying a URL Shortener function with AWS Lambda
URL shortening is a common practice in web development to create concise and user-friendly links. In this article, we'll explore how to build a serverless URL shortener using AWS Lambda. This setup will allow you to shorten long URLs into more manageable and shareable links.
Prerequisites
Before we start, make sure you have the following:
- An AWS account with access to AWS Lambda and API Gateway.
- AWS CLI installed and configured.
Steps to Create a URL Shortener
Step 1: Create a Lambda Function
Open the AWS Lambda console.
Click on "Create function."
Choose "Author from scratch."
Enter a name for your function (e.g.,
URLShortenerFunction
).Select a runtime (e.g., Node.js).
In the function code section, replace the existing code with the following Node.js code:
const { nanoid } = require('nanoid');
exports.handler = async (event) => {
const originalUrl = event.queryStringParameters.url;
const shortUrl = generateShortUrl();
// Some form of persistent logic
return {
statusCode: 200,
body: JSON.stringify({ originalUrl, shortUrl }),
};
};
function generateShortUrl() {
// Use nanoid to generate a short URL key
return 'https://short.url/' + nanoid(7);
}
This code takes a long URL as a query parameter and returns a JSON object containing the original and short URLs.
Note: A design consideration for this solution should include a form of persistence where the original URL and the shortened URL are safely stored.
Under "Basic settings," set the timeout to a reasonable value (e.g., 10 seconds).
Click "Deploy" to create the Lambda function.
Step 2: Create an API Gateway
- Open the API Gateway console.
- Click on "Create API."
- Choose "HTTP API" and click "Build" to create a new API.
- In the "Configure routes" section, click "Add integration."
- Choose "Lambda function" and select the Lambda function you created.
- Click "Create" to create the API.
Step 3: Deploy the API
- In the API Gateway console, select your API.
- Click on "Deployments" in the left sidebar.
- Click "Create" to create a new deployment.
- Choose a stage name (e.g., "prod") and click "Deploy."
Step 4: Test the URL Shortener
In the API Gateway console, navigate to the "Invoke URL" section to find your API endpoint.
Use a tool like
curl
or a web browser to make a GET request to the endpoint with theurl
query parameter:
curl "<Your API Endpoint>?url=https://www.example.com"
Replace with the actual endpoint URL.
- You should receive a JSON response containing the original and short URLs.
Congratulations! You've successfully created a serverless URL shortener using AWS Lambda and API Gateway. This example is a basic implementation, and you can enhance it by adding persistence, customizing the short URL format, and implementing redirection.