use middy to allow custom headers

1.9k Views Asked by At

I'm using middy for handling middleware for my AWS lambda code. Below is my code:

const middy = require('middy')
const middlewares = require('middy/middlewares')

const handlerWrapper = (handler) => middy((event, context, callback) => {
  context.callbackWaitsForEmptyEventLoop = false;
  let code = 200  
  context.send = (body) => callback(null,{
    statusCode: code,
    body: JSON.stringify(body)
  })

  context.status = (_code) => {
    code = _code
    return context
  }

  return handler(event, context ,callback)
}).use(middlewares.jsonBodyParser()).use(middlewares.cors())

The problem is, my front-end is sending a custom header named authorizationv2 and when my front-end tried to send a request to my AWS lambda code, the browser will display this error

Access to XMLHttpRequest at 'https://apiv2.website.com/data/list/' from origin 'http://admin.website.com' has been blocked by CORS policy: Request header field authorizationv2 is not allowed by Access-Control-Allow-Headers in preflight response.

So I assume to fix this, I need middy to allow custom header authorizationv2. I'm not entirely sure how to do this using middy.

1

There are 1 best solutions below

0
On

You need to add the custom header in the preflight response. Two ways to do it:

  • if you are using serverless framework to deploy the resources, add the custom header in the function definition as below:
    yourfunctionname:
    handler: path/to/handler
    events:
      - http:
          path: path/to/endpoint
          method: get
          cors:
            origin: "*"
            headers:
              - Content-Type
              - X-Amz-Date
              - Authorization
              - X-Api-Key
              - X-Amz-Security-Token
              - X-Amz-User-Agent
              - <your-custom-header-goes-here>
  • manual way: go to AWS API Gateway and find your API resource. Click "Action" -> "Enable CORS". on the page you can add the custom header in the field "Access-Control-Allow-Headers".