Should I use a middleware for CORS in Next.js, and how would I implement it?

Responsive Ad Header

Question

Grade: Education Subject: Support
Should I use a middleware for CORS in Next.js, and how would I implement it?
Asked by:
76 Viewed 76 Answers

Answer (76)

Best Answer
(1082)
Using a middleware for CORS in Next.js can be beneficial, especially if you have multiple API routes. Here's an example of how you can implement a CORS middleware: Create a file like `middleware/cors.js`: ```javascript export function cors(req, res, next) { res.setHeader('Access-Control-Allow-Origin', '*'); // Or your specific origin res.setHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS'); res.setHeader('Access-Control-Allow-Headers', 'Content-Type, Authorization'); if (req.method === 'OPTIONS') { res.status(200).end(); return; } next(); } ``` Then, in your API route, use it: ```javascript import { cors } from '../../middleware/cors'; export default async function handler(req, res) { cors(req, res, () => { // Your API logic here res.status(200).json({ data: 'Your data' }); }); } ``` **Important:** Middleware should be carefully implemented to ensure it only applies to API routes that require CORS. You could adapt the `cors` middleware code from the `Next.js` documentation that allows only specific origins.