Skip to content

Commit

Permalink
Cors middleware
Browse files Browse the repository at this point in the history
  • Loading branch information
Victor Fernandez committed Jan 28, 2022
1 parent 2b48325 commit eb6ac08
Showing 1 changed file with 33 additions and 0 deletions.
33 changes: 33 additions & 0 deletions cors-middleware.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
import corsWrapper from 'cors';
import { RequestHandler } from 'express';

/**
* Hey there you curious :)
*
* By default, NextJS APIs are same-site origin only.
* But since *I needed the main project*
* to have public API access, I had to configure CORS.
*
* @see https://github.com/vercel/next.js/tree/canary/examples/api-routes-cors
* @see https://github.com/expressjs/cors#configuration-options
*/
const CORS_OPTIONS = {
methods: ['GET', 'OPTIONS'],
};

function promisifyMiddleware(middleware: RequestHandler) {
return (req: any, res: any) =>
new Promise((resolve, reject) => {
middleware(req, res, (result: Error | unknown) => {
if (result instanceof Error) {
return reject(result);
}
return resolve(result);
});
});
}

// Initialize the cors middleware
const cors = promisifyMiddleware(corsWrapper(CORS_OPTIONS));

export default cors;

0 comments on commit eb6ac08

Please sign in to comment.