How To Redirect With Serverless Framework

Elliott SpiraOpen Source0 Comments

We just started playing with the v1 of the serverless framework after building a serverless hipchat plugin boilerplate repository and an example hipchat plugin that aggregates CloudWatch Alarms in version 0.5.6 of the serverless framework.

Just as it always seems to happen, a completely new, re-written version of the serverless framework was released after I wrote the boilerplate repository.

So, we decided that we would write a multi-part blog series on some of the lessons and experiences we have as we start working with Serverless v1.

Changes in V1

One of the first things I noticed when starting with version 1 of the Serverless framework is that there were no longer `s-project.json` or `s-function.json` files for each function in the project. These appear to have been replaced by a single `serverless.yml` file (yay, yaml!) at the root of the repository. This file defines a `service` (which is the unit of organisation appearing to replace a `project` in v0.x.x) and a series of functions.

Also, instead of defining and deploying endpoints individually, http endpoints have been made a type of `event` in version 1 of the Serverless framework. Events are now defined as ‘Anything that triggers an AWS lambda function to execute’, including SNS topic subscriptions, CloudWatch Alerts and S3 uploads. We think that this is a nice simplification! These are also defined for each function within the `serverless.yml` file.

We like to learn by doing, so I was thinking of a simple project to deploy my first serverless v1 project `service`. One thing that I realised would be different in a v1 project is the definition of redirects.

In a v0.x.x `project`, a redirect was easy to implement, by adding to the header section of the `s-function.json` file for the relevant endpoint. In v1, I decided to implement the changes to the header in the function itself.

Our approach to SLS V1

Check out our example code in this repository.

Of course, the one thing I don’t like about this approach is that the same response and header will be sent from the function regardless of what `event` triggered it.

Digging deeper into the Serverless documentation on APIGateway events I found that there is a way to configure header configuration just for a specific event in the `serverless.yml` file. See this approach in this pull request.

Have you found a more elegant solution to implementing http redirects in version 1 of the serverless framework? What are your thoughts on where this exciting framework is heading? Comment/tweet us to let us know! And stay tuned for more parts to come 🙂

Leave a Reply

Your email address will not be published. Required fields are marked *