How to return a 302 with Location header using API Gateway and Lambda

How can you map your Lambda success response to 302 with a Location header pointing to a new resource? Like a lot of other things with API Gateway it's easy to do but not very obvious. Let's dive in.

Here's an example of a 302 response with the Location header set to the redirect location:

> HTTP/1.1 302 Found
> Content-Type: application/json
> Content-Length: 38
> Connection: keep-alive
> Location:

Lambda code

First let's get your Lambda setup to return the value you want in the Location header. With Node you can you do something like:

exports.handler = function(event, context) {
context.succeed({location: ''});

The property name location has to match up with the value you will set later your API Gateway Integration Response.

API Gateway Method Response

When setting up the API Gateway Method Response, start by declaring the status code in the Method Response section. 200 will already be there so delete it. Add your 302 here instead and add the Location response header.

You can think of Method Response like a place for "declarations". Just like you have to declare your variables and classes before you use them in some programming languages this is what the Method Response area is for. You declare what you're going to use but you don't actually link them up to your Lambda here. Integration Response is the area where you do that so that's where you head next.

API Gateway Integration Response

In Integration Response you'll see it setup for the 200 with the Regex set to default. Delete this mapping by clicking the X icon on the right side. Now add a new integration response. You'll be prompted to choose a status code from a list of codes that were declared back in Method Response. Pick your 302. You also want to setup a Header Mapping for Location. Make the mapping value integration.response.body.location. The last part of that string "location" has to match the value you are returning in your Lambda function. Make sure you click the green check near the header mapping and the Save near the response regex.

Deploy your API and give it a shot!

Please comment below, tweet @kennbrodhagen, or email me and let me know what you're doing with API Gateway and Lambda.


Interested in more?

Sign up for my mailing list. You'll get each new article and other announcements delivered to your inbox. I promise not to spam you. Unsubscribe any time you like.

Read the next article in your inbox!

* indicates required