Skip to content

Commit 4fec2f0

Browse files
authored
add middleware (#685)
To resolve CORS error when calling the UserOpBuilder service endpoints
1 parent 6d7a2c5 commit 4fec2f0

File tree

1 file changed

+36
-0
lines changed

1 file changed

+36
-0
lines changed
Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
import { NextResponse, NextRequest } from 'next/server'
2+
3+
export function middleware(req: NextRequest) {
4+
const res = NextResponse.next()
5+
6+
const origin = req.headers.get('origin')
7+
8+
if (process.env.NODE_ENV === 'production') {
9+
// In production, allow all origins
10+
res.headers.set('Access-Control-Allow-Origin', '*')
11+
} else {
12+
// In development, only allow localhost
13+
const allowedOrigins = ['http://localhost:3000']
14+
if (origin && allowedOrigins.includes(origin)) {
15+
res.headers.set('Access-Control-Allow-Origin', origin)
16+
}
17+
}
18+
19+
// Common headers for both environments
20+
res.headers.set('Access-Control-Allow-Methods', 'GET, POST, OPTIONS')
21+
res.headers.set('Access-Control-Allow-Headers', 'Content-Type, Authorization')
22+
23+
// Handle preflight requests
24+
if (req.method === 'OPTIONS') {
25+
return new Response(null, {
26+
status: 204,
27+
headers: {
28+
'Access-Control-Allow-Origin': process.env.NODE_ENV === 'production' ? '*' : (origin || ''),
29+
'Access-Control-Allow-Methods': 'GET, POST, OPTIONS',
30+
'Access-Control-Allow-Headers': 'Content-Type, Authorization'
31+
}
32+
})
33+
}
34+
35+
return res
36+
}

0 commit comments

Comments
 (0)