hoangvvo / next-connect

The TypeScript-ready, minimal router and middleware layer for Next.js, Micro, Vercel, or Node.js http/http2
https://www.npmjs.com/package/next-connect
MIT License
1.63k stars 65 forks source link

Cors in next.js API routes - does not seem to work? #127

Closed w90 closed 3 years ago

w90 commented 3 years ago

Did anyone get the next-connect package to work with cors package and the relatively new next.js feature - API routes?

pages/api/process file:

import nextConnect from 'next-connect';
import Cors from 'cors'

const apiRoute = nextConnect();

apiRoute
  .use(Cors())

  .post((req, res) => {
    res.status(200).json({ text: 'OK' })
  })

export default apiRoute;

Additional settings in next.config.js:

module.exports = {
  async headers() {
    return [
      {
        source: '/api/process',
        headers: [
          {
            key: 'Access-Control-Allow-Origin',
            value: 'https://external-webpage.com',
          },
          {
            key: 'Vary',
            value: 'Origin',
          },
        ],
      },
    ]
  },
}

I'm getting cors related errors. I might be doing something wrong, if so please correct me!

Meanwhile, when using example from next.js repo, which does not utilize next-connect library, all works just fine:

Any advice will be much appreciated, as I'd rather use next-connect solution which is imo a bit cleaner than the one provided by the next.js team.

hoangvvo commented 3 years ago

I am also using the cors package and have no problems. What errors are you seeing?

w90 commented 3 years ago

Hello, thanks for the reply. It's the standard cors error,

Access to XMLHttpRequest at '................' from origin '.................' 
has been blocked by CORS policy: No 'Access-Control-Allow-Origin' 
header is present on the requested resource.

As I stated in my detailed post above, all works fine when using the next.js example, without next-connect. Could you maybe paste here, what is your exact implementation, when using next.js API Routes? Much appreciated!

hoangvvo commented 3 years ago

@w90 Hey, I could not reproduce this issue: https://codesandbox.io/s/next-connect-with-cors-package-guned?file=/pages/api/index.js

image

Please provide a complete reproduction if possible. Thanks!

w90 commented 3 years ago

Hello Hoang, thanks a lot for the reply! I've found the bug in the code - it was the missing trailing slash on the original api endpoint /api/process. Everything works perfect! I'm closing the issue. Peace!