To install the package, run:
npm install @daveyplate/next-cors-middleware
To use the middleware in your Next.js App, follow these steps:
-
Create a
middleware.js
file in the root of your project:import { NextResponse } from 'next/server' import { nextCors } from '@daveyplate/next-cors-middleware' export function middleware(request) { const response = nextCors({ request, allowedOrigins: ['https://example.com', 'https://anotherdomain.com'], }) if (response) { return response } // Your middleware logic here return NextResponse.next() }
-
Customize the
allowedOrigins
array with the domains you want to allow. -
Optionally, you can pass custom CORS options:
const customCorsOptions = { 'Access-Control-Allow-Methods': 'GET, POST', 'Access-Control-Allow-Headers': 'Content-Type, Authorization, X-Custom-Header', }; export function middleware(request) { const response = nextCors({ request, allowedOrigins: ['https://example.com'], corsOptions: customCorsOptions, }); if (response) { return response; } // Your middleware logic here return NextResponse.next(); }
That's it! Your Next.js App Router now supports CORS.