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