Skip to content

Instantly share code, notes, and snippets.

@schoenfelde
Created April 11, 2020 14:49
Show Gist options
  • Save schoenfelde/7961a8cf9656799b59c7393dfbc450d7 to your computer and use it in GitHub Desktop.
Save schoenfelde/7961a8cf9656799b59c7393dfbc450d7 to your computer and use it in GitHub Desktop.
CORS for Serverless
import { APIGatewayProxyHandler, Context, Callback } from 'aws-lambda';
interface LambdaResponse {
body: any,
statusCode?: number
}
type Lambda = (event?: any, context?: Context, callback?: Callback) => Promise<LambdaResponse>
export interface LambdaConfig {
handler: Lambda
allowCredentials: boolean
}
const ALLOWED_ORIGINS = [ ]
const generateCORSHeaders = (event:any, config: LambdaConfig) => {
const requestOrigin = (event && event.headers && event.headers.origin || "")
const allowedOrigin = ALLOWED_ORIGINS.find( origin => origin === requestOrigin)
if (allowedOrigin) {
let headers = {
"Access-Control-Allow-Origin": allowedOrigin
}
if (config.allowCredentials)
headers["Access-Control-Allow-Credentials"] = true
return headers
}
else return { }
}
export default (config: LambdaConfig):APIGatewayProxyHandler => async (event, context, cb) => {
console.log("Request Received");
const response = await config.handler(event, context, cb);
console.log("Response:", response);
return {
body: JSON.stringify(response.body),
statusCode: response.statusCode || 200,
headers: generateCORSHeaders(event, config)
}
}
//Used like so, where handler is your custom lambda function
const entry = rootHandler({
handler: async () => ({ body: "Hello World" }),
withCredentials: true
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment