Amin
Amin
KKinde
Created by Amin on 5/31/2024 in #💻┃support
next.js 14 hostinger vps nginx pm2 - CORS related issues
and this is my middleware to apply CORS headers: import { NextRequest, NextResponse } from "next/server"; const allowedOrigins = ["https://housifa.com", "https://housifa.kinde.com"]; const corsOptions = { "Access-Control-Allow-Methods": "GET, POST, PUT, DELETE, OPTIONS", "Access-Control-Allow-Headers": "Content-Type, Authorization", "Access-Control-Allow-Credentials": "true", // Allow credentials }; export function middleware(request: NextRequest) { const origin = request.headers.get("origin"); if (origin && allowedOrigins.includes(origin)) { if (request.method === "OPTIONS") { // Handle preflight request const preflightHeaders = { "Access-Control-Allow-Origin": origin, ...corsOptions, }; return NextResponse.json({}, { headers: preflightHeaders }); } // Handle actual request const response = NextResponse.next(); response.headers.set("Access-Control-Allow-Origin", origin); Object.entries(corsOptions).forEach(([key, value]) => { response.headers.set(key, value); }); return response; } // If origin is not allowed, return a response without CORS headers return NextResponse.next(); } export const config = { matcher: "/:path*", };
3 replies