Skip to content

Instantly share code, notes, and snippets.

@gilbarbara
Created August 16, 2022 00:07
Show Gist options
  • Save gilbarbara/9c63f8aea9f42dabab1fcdd3defcf6f7 to your computer and use it in GitHub Desktop.
Save gilbarbara/9c63f8aea9f42dabab1fcdd3defcf6f7 to your computer and use it in GitHub Desktop.
Vercel cors helper
export function cors(fn: NextApiHandler, methods = ['GET']) {
return async (request: NextApiRequest, response: NextApiResponse) => {
const allowedMethods = [...methods, 'OPTIONS'].join(',');
response.setHeader('Access-Control-Allow-Credentials', 'true');
response.setHeader('Access-Control-Allow-Origin', '*');
response.setHeader('Access-Control-Allow-Methods', allowedMethods);
response.setHeader(
'Access-Control-Allow-Headers',
'X-CSRF-Token, X-Requested-With, Accept, Accept-Version, Authorization, Content-Length, Content-MD5, Content-Type, Date, X-Api-Version',
);
if (request.method === 'OPTIONS') {
return response.status(200).end();
}
return fn(request, response);
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment