nextjs-cors
raw JSON →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.
Common errors
error TypeError: NextCors is not a function ↓
error Error: Cannot find module 'nextjs-cors' ↓
error CORS request failed with status 500: "Cannot set headers after they are sent to the client" ↓
Warnings
breaking Requires Next.js >=8.1.1-canary.54. Older versions may not support the async handler pattern used. ↓
deprecated OptionsSuccessStatus option: using it defaults to 200 but modern browsers expect 204. Consider omitting or setting to 204. ↓
gotcha The underlying cors package's origin option might not work as expected with wildcard '*' when credentials are required. Must explicitly set origin for credentialed requests. ↓
gotcha Importing with CommonJS require requires .default access. ↓
gotcha If using TypeScript and you see 'Could not find a declaration file for module', ensure types are installed (they are bundled, but tsconfig may need to be configured). ↓
Install
npm install nextjs-cors yarn add nextjs-cors pnpm add nextjs-cors Imports
- NextCors wrong
const NextCors = require('nextjs-cors')correctimport NextCors from 'nextjs-cors' - NextCors wrong
import { NextCors } from 'nextjs-cors'correctimport NextCors from 'nextjs-cors' - require wrong
const NextCors = require('nextjs-cors')correctconst NextCors = require('nextjs-cors').default
Quickstart
import NextCors from 'nextjs-cors';
import type { NextApiRequest, NextApiResponse } from 'next';
export default async function handler(
req: NextApiRequest,
res: NextApiResponse
) {
await NextCors(req, res, {
methods: ['GET', 'HEAD', 'PUT', 'PATCH', 'POST', 'DELETE'],
origin: '*',
optionsSuccessStatus: 200,
});
res.json({ message: 'Hello NextJs Cors!' });
}