Adds Cross Origin Resource Sharing (CORS) support to Lambda Controller.
To Install
npm i @dotmh/lambda-controller-cors
Requires Lambda Controller to be installed. Lambda Controller is a peer dependancy and so won't be installed automatically
The CORS plugin usage is slightly different to other plugins. To use CORS I recommend it you add it to the contrustor of your controller.
i.e.
const Controller = require('@dotmh/lambda-controller');
const cors = require('@dotmh/lambda-controller-cors');
class MyController extends Controller {
constructor(event, ctx, cb) {
super(event,ctx,cb);
this.add(cors());
this.cors();
}
}
This will add the cors plugin and configure the cors headers.
You will notice that we call a function to add, this is because the cors plugin supplies a factory unlike other plugins.
The CORS plugin supplies a factory unlike other Lambda Controller plugins. This is so that you can pass it a configuration. The CORS plugin takes a list of allowed origins that CORS requests can come from.
// .... your controller class
this.add(cors({
allowed: [
'localhost',
'prod.example.com',
'dev.example.com'
]
}});
// ... the rest of your controller
allowed
accepts ether a list of allowed domains , a single domain or a ''. Whent the '' is used cors is added to all hosts i.e. allow all.
To fully support CORS in AWS API Gateway we have to do some extra configuration. If you are using the Servless Framework.
CORS uses a preflight to the route to get the CORS headers before making a full request. To support this we have to configure the a route for options. To support this the mixin automatically adds a cors route handler to your controller called corsOptions
. So we need to configure a handler for that
module.exports.corsOptions = function (event, ctx, callback) {
(new Controller(event, ctx, callback)).corsOptions();
};
and then add that as an http event in the serverless.yml
functions:
corsOptions:
handler: handler.corsOptions
events:
- http:
path: "/"
method: options
cors:
origin: '*'
headers:
- Content-Type
- X-Amz-Date
- Authorization
- X-Api-Key
- X-Amz-Security-Token
- X-Amz-User-Agent
allowCredentials: true
API Gateway needs to know what it should do with CORS requests. I.e. it needs enabling. This has to be done on everyone of your route
To do this you have to add the cors property to your route.
cors:
origin: '*'
headers:
- Content-Type
- X-Amz-Date
- Authorization
- X-Api-Key
- X-Amz-Security-Token
- X-Amz-User-Agent
allowCredentials: true
PLEASE NOTE I hope to update this readme with the steps required when using AWS SAM soon.
For the API documentation see https://dotmh.github.io/lambda-controller-cors/
Or to read locally
npm run readdocs
This package is Treeware. If you use it in production, then we ask that you buy the world a tree to thank us for our work. By contributing to the Treeware forest you’ll be creating employment for local families and restoring wildlife habitats.
Logo design by @dotmh