Skip to content

Feature request: Implement CORS middleware for REST API #4446

@svozza

Description

@svozza

Use case

We should have a middleware that adds CORS headers to responses. The middelware should have sane defaults than can be overridden when initilising the middleware.

Solution/User Experience

The middleware will be applied like any other:

import {cors} from from '@aws-lambda-powertools/event-handler/rest/middleware';

// use defaults
app.use(cors());

// custom configuration
app.use(cors({
  allowHeaders: ['X-My-Header'],
  allowMethods: ['GET', 'POST', 'OPTIONS'],
  credentials: true,
  exposeHeaders: ['Content-Length'],
  maxAge: 300,
  origin: 'http://mysite.com',
}));

As per the Python implementation the defaults are:

{
  origin: '*',
  allowHeaders: ['Authorization', 'Content-Type', 'X-Amz-Date', 'X-Api-Key', 'X-Amz-Security-Token'],
  allowMethods: ['DELETE', 'GET', 'HEAD', 'PATCH', 'POST', 'PUT'  ],
  exposeHeaders: [],
  credentials: false,
}

Pre-flight (OPTIONS) calls are typically handled at the API Gateway or Lambda Function URL so no Lambda integration is necessary. However, ALB expects you to handle pre-flight requests so our implementation should still check for the OPTIONS verb and short-circuit so that we can future proof. This involves returning a Web Response with the necessary headers and a HTTP status code of 204.

Alternative solutions

Acknowledgment

Future readers

Please react with 👍 and your use case to help us understand customer demand.

Metadata

Metadata

Assignees

Labels

event-handlerThis item relates to the Event Handler Utilityfeature-requestThis item refers to a feature request for an existing or new utilityhelp-wantedWe would really appreciate some support from community for this one

Type

No type

Projects

Status

Coming soon

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions