-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Victor Fernandez
committed
Jan 28, 2022
1 parent
2b48325
commit eb6ac08
Showing
1 changed file
with
33 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; |