1.1.1 • Published 5 years ago

lambda-proxy-cors v1.1.1

Weekly downloads
2
License
MIT
Repository
github
Last release
5 years ago

Lambda Proxy CORS

Enable straightforward CORS for your node.js AWS Lambda Proxy handler, with this extremely lightweight module. Available on npm.

Install

npm i lambda-proxy-cors

Usage

This module supports the async style. If you're using the callback style, see the migration guide below.

Wrap your existing handler with cors:

const { cors } = require('lambda-proxy-cors');

exports.handler = cors(async (event, context) => {
  console.log(JSON.stringify(event, null, 2));
  console.log(JSON.stringify(context, null, 2));

  return {
    body: 'Hello, World!',
    statusCode: 200
  };
});

Custom CORS headers

This module provides the following default headers in the response:

'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'GET,HEAD,PUT,PATCH,POST,DELETE',

These headers are easy to override and extend. Like so:

const { cors } = require('lambda-proxy-cors');

exports.handler = cors(async (event, context) => {
  return {
    body: 'Hello, World!',
    headers: {
      'Access-Control-Allow-Methods': 'GET', 
      'x-my-header': 'my-value',
    },
    statusCode: 200
  };
});

Migrating away from callback style

Take the following callback version:

exports.handler = (event, context, callback) => {
  console.log(JSON.stringify(event, null, 2));
  console.log(JSON.stringify(context, null, 2));

  const res = {
    body: 'Hello, World!',
    statusCode: 200
  };

  callback(null, res);
}

Convert it to async, like so:

exports.handler = async (event, context) => {
  console.log(JSON.stringify(event, null, 2));
  console.log(JSON.stringify(context, null, 2));

  return {
    body: 'Hello, World!',
    statusCode: 200
  };
};

And then you can wrap with cors:

const { cors } = require('lambda-proxy-cors');

exports.handler = cors(async (event, context) => {
  console.log(JSON.stringify(event, null, 2));
  console.log(JSON.stringify(context, null, 2));

  return {
    body: 'Hello, World!',
    statusCode: 200
  };
});

License

MIT.

1.1.1

5 years ago

1.0.1

5 years ago

1.0.0

5 years ago