CORS middleware for Next.js API routes, built on top of the popular Express cors package. Current stable version is 2.2.1, released as a patch update preparing for the next major version. Provides a simple, drop-in solution to enable Cross-Origin Resource Sharing in Next.js API routes with all standard cors options (methods, origin, allowed headers, etc.). Uses an async middleware pattern that fits naturally into Next.js API route handlers. Unlike generic cors packages, nextjs-cors is specifically designed for Next.js's request/response model and does not require wrapping or additional configuration to work with Edge Runtime (though support depends on underlying cors). Ships TypeScript definitions, making it easy to use in TS projects. Peer dependency on Next.js >=8.1.1-canary.54, ensuring compatibility with older versions. Compared to other Next.js CORS solutions like next-connect or manual headers, nextjs-cors offers a minimal API and leverages the well-tested cors package.
npm install nextjs-corsVerified import paths — ran on the pinned version, not inferred.
Demonstrates how to use nextjs-cors as middleware in a Next.js API route with CORS options.
Upgrade Next.js to at least 8.1.1-canary.54 or use an older version of nextjs-cors.
Remove optionsSuccessStatus or set to 204: optionsSuccessStatus: 204
Set origin to a specific domain instead of '*' when using credentials: true.
Use const NextCors = require('nextjs-cors').default;Check that your tsconfig includes 'node_modules/@types' or set 'moduleResolution': 'node'.
Use import NextCors from 'nextjs-cors' or const NextCors = require('nextjs-cors').default;Run npm install nextjs-cors --save or yarn add nextjs-cors.
Ensure NextCors is called early in the handler, and do not call res.end() before it.