Chekkan's Blog

Access response headers in HTTP Fetch API with Serverless Framework and AWS Lambda

November 30, 2017 - 1 min read

In order to access response headers such as Location in HTTP Fetch api whilst using Serverless Framework and AWS Lambda Functions with CORS enabled, you need to do the following.

  1. Make sure cors is set to true on serverless.yml
  2. Make sure in the response header, you are returning the following:

    callback(null, {
       statusCode: 201,
       headers: {
           'Access-Control-Allow-Origin': '*',
           // Required for cookies, authorization headers with HTTPS
           'access-control-allow-credentials': true,
           'access-control-allow-headers': 'Location',
           'access-control-expose-headers': 'Location',
           Location: id
       }
    })

Now, you can access the header location from fetch.

this.httpClient.fetch("/users", {
    method: "post",
    body: json({ username: "chekkan" }),
})
.then((res) => {
    return res.headers.get("location")
})

References:

Photo by Paul Buffington on Unsplash


Harish H. Babu

Written by Harish H. Babu who lives and works in Cardiff engineering software things. You should follow him on Twitter