Skip to content

Commit b6dcdf2

Browse files
authored
Merge pull request #381 from developmentseed/enable-cors
allowing CORS in API
2 parents 7b7dc53 + 116f10f commit b6dcdf2

File tree

3 files changed

+30
-0
lines changed

3 files changed

+30
-0
lines changed

next.config.js

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,27 @@ const vercelUrl =
33
`https://${process.env.NEXT_PUBLIC_VERCEL_URL}`
44

55
module.exports = {
6+
async headers() {
7+
return [
8+
{
9+
// matching all API routes
10+
// link: https://vercel.com/guides/how-to-enable-cors#enabling-cors-in-a-next.js-app
11+
source: '/api/:path*',
12+
headers: [
13+
{ key: 'Access-Control-Allow-Credentials', value: 'true' },
14+
{ key: 'Access-Control-Allow-Origin', value: '*' },
15+
{
16+
key: 'Access-Control-Allow-Methods',
17+
value: 'GET,OPTIONS,PATCH,DELETE,POST,PUT',
18+
},
19+
{
20+
key: 'Access-Control-Allow-Headers',
21+
value: '*',
22+
},
23+
],
24+
},
25+
]
26+
},
627
serverRuntimeConfig: {
728
DEFAULT_PAGE_SIZE: 10,
829
NODE_ENV: process.env.NODE_ENV || 'development',

src/middlewares/base-handler.js

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -58,6 +58,11 @@ export function createBaseHandler() {
5858
})
5959
},
6060
onNoMatch: (req, res) => {
61+
if (req.method === 'OPTIONS') {
62+
logger.info('OPTIONS request')
63+
return res.status(200).end()
64+
}
65+
6166
res.status(404).json({
6267
statusCode: 404,
6368
error: 'Not Found',

src/pages/api/[[...slug]].js

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,10 @@ handler.get('api/', (_, res) => {
1414
res.status(200).json({ version: packageJson.version })
1515
})
1616

17+
handler.options('api/*', (_, res) => {
18+
res.status(200).end()
19+
})
20+
1721
manageRouter(handler)
1822

1923
export default handler

0 commit comments

Comments
 (0)