Living on the edge

Deepan Subbiah
2 min readMar 13, 2018

AWS’s Lambda@Edge service is a nifty tool to implement push state routing support for your single page applications.

So the requirement in general is to be able to map a URL like https://your-domain/app-name/app-route to the single page app’s index.html that then loads/initialises the application and renders the appropriate view for the URL.

If you are serving the application off a web server, then you could configure appropriate redirects to handle this. However, if you are using a CloudFront/S3 configuration, this was previously a pain as it forced you to now setup an EC2 instance or another mechanism to handle this redirection. Enter Lambda@Edge and you now have an alternative!

Lambda@Edge is a compute service that allows you to map CloudFront events to Lambda functions. You can map functions to both inbound and outbound events and attach them to CloudFront behaviours. The functions themselves are called with parameters that contain the request details and can hence redirect a request to a specific S3 bucket asset (in our case, the single page app’s index.html) conditionally.

So say you had a CloudFront behaviour with the path pattern as ‘app-name/*’ to handle your application requests, the following Lambda@Edge snippet will redirect requests without an extension to the app’s index.html.

const path = require(‘path’)exports.handler = (evt, ctx, cb) => {
const { request } = evt.Records[0].cf

if (!path.extname(request.uri)) {
request.uri = ‘/app-name/index.html’

cb(null, request)

You can now attach this lambda to the behaviour and you have routing to support push state!

Life on the edge!