How to use Middleware in Next.js API Routes In Next.js
Next.js API routes, we can use middleware to handle CORS.
// pages/api/hello.js
import Cors from 'cors'
// Initialize the cors middleware
const cors = Cors({
methods: ['GET', 'HEAD', 'POST'],
// Replace with your domain
origin: 'https://yourdomain.com',
credentials: true
})
// Helper method to wait for middleware to execute before continuing
function runMiddleware(req, res, fn) {
return new Promise((resolve, reject) => {
fn(req, res, (result) => {
if (result instanceof Error) {
return reject(result)
}
return resolve(result)
})
})
}
export default async function handler(req, res) {
// Run the middleware
await runMiddleware(req, res, cors)
// Rest of your API logic here
res.json({ message: 'Hello Everyone!' })
}
How to Fix CORS Errors in Next.js and Vercel?
Cross-Origin Resource Sharing (CORS) is a security feature that restricts web apps from making requests to a different domain than the one that served the web page to it. This is needed for security, although sometimes it can block legitimate requests, especially when working with APIs. In this article, we will learn fixing the CORS errors in the Next.js application deployed on Vercel.