CORS
CORS errors happen when you're trying to access resources from one domain on another domain. It only happens in the browser, and is a security feature.
So essentially, when you're fetching data from https://superheroapi.com/api/1
while on localhost:3000
, the browser first asks superheroapi.com
, "hey, can this domain fetch data from you?". superheroapi.com
will then say, "I only accept requests from these domains". If localhost:3000
is not in that list, you'll get a CORS error.
https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS
You can change the domains that superheroapi.com
accepts via the Access-Control-Allow-Origin
header. You can do it manually, or there's a handy npm package that will take care of that for you in Next.js.
Fix CORS in Next.js
By default in Next.js, the CORS header is restricted to same-domain traffic only. However, you can change this.
Next.js actually has a guide in their docs on adding a CORS header to api routes.
https://nextjs.org/docs/api-routes/api-middlewares#connectexpress-middleware-support
In short, though, first install the CORS package.
npm i cors
# or
yarn add cors
# or
pnpm add cors
Then add it to the API route.
import Cors from 'cors'
// Initializing the cors middleware
const cors = Cors({
methods: ['GET', 'HEAD'],
})
// Helper method to wait for a middleware to execute before continuing
// And to throw an error when an error happens in a middleware
function runMiddleware(req, res, fn) {
return new Promise((resolve, reject) => {
fn(req, res, (result) => {
if (result instanceof Error) {
return reject(result)
}
return resolve(result)
})
})
}
async function handler(req, res) {
// Run the middleware
await runMiddleware(req, res, cors)
// Rest of the API logic
res.json({ message: 'Hello Everyone!' })
}
export default handler
Code snippets are taken from the Next.js docs. All credit goes to the makers of Next.js for them.