No 'Access-Control-Allow-Origin' header is present on the requested resource. Next.js CORS error when using next-connect

390 views Asked by At

I am trying to use cors in Next.js with next-connect. However, I'm unable to make it work.

Here's my cors code:

function handler() {
  if (!COOKIE_SECRET || !SESSION_SECRET)
    throw new Error(
      `Please add COOKIE_SECRET & SESSION_SECRET to your .env.local file!`
    )

  return nc<NextIronRequest, NextApiResponse>({
    onError: (err, _, res) => {
      error(err)
      res.status(500).end(err.toString())
    },
  })
    .use(
      cookieSession({
        name: 'session',
        keys: [COOKIE_SECRET],
        maxAge: 24 * 60 * 60 * 1000 * 30,
        secure: IS_PRODUCTION && !process.env.INSECURE_AUTH,
        signed: IS_PRODUCTION && !process.env.INSECURE_AUTH,
      })
    )
    .use((req,res,next)=> {
      console.log('cors')
      res.setHeader("Access-Control-Allow-Origin", "*")
      res.setHeader(
        "Access-Control-Allow-Headers",
        "Origin, X-Requested-With, Content-Type, Accept, Authorization"
      );
      if (req.method == "OPTIONS") {
        res.setHeader("Access-Control-Allow-Methods", "PUT, POST, PATCH, DELETE, GET");
        return res.status(200).json({});
      }
      next()
    })
}

export default handler

FWIW, I've tried every other solution mentioned on StackOverflow like https://stackoverflow.com/a/35317615/6141587

I've also tried installing packages like cors & nextjs-cors but getting the same error:

Access to fetch at 'https://api.twitter.com/oauth/authorize?oauth_token=xxxxxxxxxxxx' (redirected from 'http://localhost:3000/api/twitter/generate-auth-link') from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

I have a Github reproduction here → https://github.com/deadcoder0904/twitter-api-v2-3-legged-login-using-next-connect (see the latest commit for cors)

I've checked Network's Tab but seeing no headers being set in there. I've also added console.log('cors') but it isn't printed there.

I guess the middleware server/api-route.ts file isn't called at all.

I need that file to be middleware. How do I solve it?

1

There are 1 answers

0
deadcoder0904 On BEST ANSWER

I wasn't actually calling the middleware. It was in another file.

I removed cookie-session & kept next-iron-session as I only need 1 session library.

Then I made the export in api/twitter/generate-auth-link routes as a wrapper to handler().get(generateAuthLink) function instead of just generateAuthLink.

And then I changed the frontend to not use fetch but instead use Link.

This fixed it!