-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathcors-middleware.ts
More file actions
33 lines (29 loc) · 900 Bytes
/
cors-middleware.ts
File metadata and controls
33 lines (29 loc) · 900 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
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