1
+ import { NextResponse } from "next/server" ;
2
+ import type { NextRequest } from "next/server" ;
3
+
4
+ export function corsMiddleware ( request : NextRequest ) {
5
+ // Get the origin from the request headers
6
+ const origin = request . headers . get ( "origin" ) || "" ;
7
+
8
+ // Define allowed origins
9
+ const allowedOrigins = [
10
+ "http://localhost:3000" ,
11
+ "http://localhost:3001" ,
12
+ // Add your production domains here
13
+ process . env . NEXT_PUBLIC_APP_URL ,
14
+ ] . filter ( Boolean ) ;
15
+
16
+ // Check if the origin is allowed
17
+ const isAllowedOrigin = allowedOrigins . includes ( origin ) ;
18
+
19
+ // Handle OPTIONS (preflight) requests
20
+ if ( request . method === "OPTIONS" ) {
21
+ return new NextResponse ( null , {
22
+ status : 204 ,
23
+ headers : {
24
+ "Access-Control-Allow-Origin" : isAllowedOrigin ? origin : allowedOrigins [ 0 ] ,
25
+ "Access-Control-Allow-Methods" : "GET, POST, PUT, DELETE, OPTIONS" ,
26
+ "Access-Control-Allow-Headers" : "Content-Type, Authorization" ,
27
+ "Access-Control-Max-Age" : "86400" ,
28
+ } ,
29
+ } ) ;
30
+ }
31
+
32
+ // Handle actual requests
33
+ const response = NextResponse . next ( ) ;
34
+
35
+ // Add CORS headers
36
+ response . headers . set (
37
+ "Access-Control-Allow-Origin" ,
38
+ isAllowedOrigin ? origin : allowedOrigins [ 0 ] ,
39
+ ) ;
40
+ response . headers . set ( "Access-Control-Allow-Credentials" , "true" ) ;
41
+ response . headers . set (
42
+ "Access-Control-Allow-Methods" ,
43
+ "GET, POST, PUT, DELETE, OPTIONS" ,
44
+ ) ;
45
+ response . headers . set ( "Access-Control-Allow-Headers" , "Content-Type, Authorization" ) ;
46
+
47
+ return response ;
48
+ }
0 commit comments