Home

Awesome

Serverless URL Shortener

A lightweight URL shortener built with the Serverless Framework using AWS Lambda and S3. Each URL redirection is stored as an S3 object with the Website-Redirect-Location metadata key set to the forwarding web address. AWS Lambda is used to create an API to save these objects. The website is served from the same S3 bucket.

Screenshot

Setup

Install dependencies

Head on over to the Serverless Framework docs and run through their quick-start guide. It’s mentioned in there as part of your setup, but be sure to install the AWS CLI and configure your AWS credentials. Then run npm install to get the NPM dependencies for the project.

Setup Route 53

Create Route 53 hosted zones for both the API and website.

Add environment variables

Create a copy of .env.example for each "stage" that you wish to deploy to (e.g .env.staging, .env.production) and then customise each configuration file as appropriate for your setup.

NameDescriptionRequired
BUCKETS3 bucket that will store URL redirectsY
REGIONAWS region to deploy toY
API_URLAPI endpoint the website will interact withY
API_DOMAINCustom API domain the API will be served fromY
API_HOSTED_ZONEAWS Route53 hosted zone ID with the custom API domainY
API_CERTIFICATE_NAMEAWS Certificate Authority certificate name for API domainY
API_BASE_ENDPOINTAPI Gateway base path (e.g. prefix) for lambda functionY
SHORT_URLBase URL of shortened links (without trailing slash)Y
SHORT_DOMAINCustom short domain to serve the websiteY
SHORT_HOSTED_ZONEAWS Route53 hosted zone ID with the custom short domainY
SHORT_DOMAIN_ACM_ARNAWS Certificate Authority certificate name for short domainY
TITLECustomize the title of the website and formN
CREDITCustomize the credit name in the footerN
CREDIT_URLCustomize the credit link in the footerN
AWS_PROFILEAWS profile setup in ~/.aws/credentialsN

Deploy API

Run npm run deploy to deploy the API and website to AWS. The resources defined in serverless.yml will be automatically instantiated using CloudFormation. Prefix with the stage you want to deploy (e.g. STAGE=production npm run deploy).

Architecture based on serverless-aws-static-websites:

Architecture

Build template

Run npm run build to build the template with appropriate template variables.

Deploy website

Run npm run deploy:client to deploy the website using the AWS CLI.

You can add a ?vanity= query string parameter to the homepage to specify a vanity (custom) shortcode instead of a randomly-generated one. If the name is already taken, a random one will be used instead.

Libraries used