Living on the edge

Deepan Subbiah
Mar 13, 2018 · 2 min read

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!

Image for post
Image for post

Life on the edge!

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store