Next.js Discord

Discord Forum

Access to XMLHttpRequest has been blocked by CORS policy.

Unanswered
ABUL KALAM posted this in #help-forum
Open in Discord
Avatar
I am facing an issue in my Next 12 application related to CORS.
Access to XMLHttpRequest at 'https://verifications.unodc.co/api/' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: Redirect is not allowed for a preflight request.

Is my configuration correct?
pages/api/index.js
const handler = nextConnect().use(
  Cors({
    origin: [process.env.NEXT_PUBLIC_API_URL],
    methods: ["GET", "POST", "PUT"],
    allowedHeaders: [
      "Origin",
      "X-Requested-With",
      "Content-Type",
      "Accept",
      "Authorization",
    ],
    credentials: false,
  })
);

.env
NEXT_PUBLIC_API_URL=https://verifications.unodc.co

66 Replies

Avatar
Is there any specific reason for using Page dir?
its a cors error, can I know where are you importing nextConnect from
Avatar
It's an old project from a client in Next 12.
Avatar
import Cors from "cors";
import nextConnect from "next-connect";
Avatar
I’m unsure about that. But to resolve this error, you need to pass Access control allow origin error
Avatar
The issue is actually in the production. The application is deployed on Vercel and I get this error there:
POST https://unodc-org.vercel.app/api 405 (Method Not Allowed)
Uncaught (in promise) Error: Request failed with status code 405
And when I try to access that api from localhost, I get this error:
Access to XMLHttpRequest at 'https://unodc-org.vercel.app/api/' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: Redirect is not allowed for a preflight request

POST https://unodc-org.vercel.app/api/ net::ERR_FAILED

Uncaught (in promise) Error: Network Error
Avatar
Löwchen
@ABUL KALAM
I'm not sure if this will work but I think it will.
{
  "headers": [
    {
      "source": "/(.*)",
      "headers": [
        { "key": "Access-Control-Allow-Origin", "value": "https://verifications.unodc.co" },
        { "key": "Access-Control-Allow-Methods", "value": "GET, POST, OPTIONS" },
        { "key": "Access-Control-Allow-Headers", "value": "Origin, X-Requested-With, Content-Type, Accept, Authorization" }
      ]
    }
  ]
}
Add this to your vercel.json or create it if you don't have it in the directory and deploy it to prod
Avatar
Let me try...
Avatar
Still getting the error. The things is, these headers are set in the index.js file and also in the next.config.js . Let me share those files with you.
Avatar
index.js
const handler = nextConnect().use(
  Cors({
    origin: true,
    methods: ["GET", "POST", "PUT"],
    allowedHeaders: [
      "Origin",
      "X-Requested-With",
      "Content-Type",
      "Accept",
      "Authorization",
    ],
    credentials: true,
  })
);


/** @type {import('next').NextConfig} */
const nextConfig = {
  reactStrictMode: true,
};

module.exports = nextConfig;
module.exports = {
  async headers() {
    return [
      {
        // matching all API routes
        source: "/api/:path*",
        headers: [
          { key: "Access-Control-Allow-Credentials", value: "true" },
          { key: "Access-Control-Allow-Origin", value: "*" },
          { key: "Access-Control-Allow-Methods", value: "GET,OPTIONS,PATCH,DELETE,POST,PUT" },
          { key: "Access-Control-Allow-Headers", value: "X-CSRF-Token, X-Requested-With, Accept, Accept-Version, Content-Length, Content-MD5, Content-Type, Date, X-Api-Version" },
        ]
      }
    ]
  }
};
Avatar
the backend at verifications.unodc.co/api/ needs to set the cors headers. if they don't do it, there is nothing you can do.
Avatar
The thing is, those headers were set in 2 different files, index.js and next.config.js. Now @Löwchen suggested setting them in vercel.json.
Still not working
Avatar
yes because setting the headers in your app is useless. it's the backend that needs to set the headers, not you. contact the person behind that backend and have them add the headers. if they don't do that, there is nothing you can do.
well, you can make a proxy using nextjs rewrites, if you are willing to – there should be plenty of guides on that
Avatar
I have access to the backend. This is the next.js application and there is /api folder there.
Avatar
so you own/have write access to verifications.unodc.co?
the thing that needs to set the header is unodc
if unodc doesn't do that, you must make a proxy through your own server
and unodc seems to be an office of the United Nations so chances are they won't do that
Avatar
Yeah,
verifications.unodc.co is one of the domains on vercel. The other one is unodc-org.vercel.app
Image
Avatar
hmm, so the error should occur on the browser console. when it occurs, which domain are you on?
Avatar
Yeah, the error occurs in the browser console.
I am now using unodc-org.vercel.app everywhere. Let me have another try.
Avatar
you are fetching your own api right? then just drop the domain
ignore all the cors header shenanigans and just fetch from "/api" instead of "https://unodc-org.vercel.app/api"
but if you want to fetch from https://unodc-org.vercel.app/api, then the cors header needs to contain exhaustively all domains that you plan to fetch the backend from
so { "key": "Access-Control-Allow-Origin", "value": "https://verifications.unodc.co" }, here you need to add more domains than just this .co one
Avatar
If the domains are different, I get the CORS error I shared above.

Now the domains are same i.e. https://unodc-org.vercel.app/org to https://unodc-org.vercel.app/api.
Now I get this error:
POST https://unodc-org.vercel.app/api 405 (Method Not Allowed)
nice idea. let me try it.
Avatar
405 means the cors works there and the /api route just doesn't accept POST requests
what does the /api route code look like?
Avatar
/api/index.js looks like this.
Image
And I also want to mention that localhost:3000 to localhost:3000/api works fine and I don't get any of the errors.
Avatar
can you show me your folder structure?
your code, just this, looks fine ...
it's bizarre that i get a html response from GET /api, that should not happen, it could be a 500 response but it should not be a html response
Avatar
Image
Avatar
does /api/document work?
also try rebuilding on vercel, what does the build log look like
Avatar
I am trying this solution.
Avatar
it will fix the cors error but it wont help the 405
Avatar
Wait a second. Let me show it to you
Image
Should I try using Postman?
Avatar
ok that's a bit too many warnings and it pushed the relevant info out of the view. could you screenshot the part that looks like this
Image
yeah, does it return 405 or 500?
Avatar
I tried on https://unodc-org.vercel.app/org
GET returns 500 with html
POST returns 405
Image
Avatar
yeah that makes sense because that is a page not an api route. try an api route (/api/...)
this looks normal though, im confused why the 405 happens
Avatar
I am sorry, I entered the wrong url here. I actually tried on https://unodc-org.vercel.app/api
Interestingly, on http://localhost:3000/api I am getting 200 on both GET and POST.
Avatar
do you have a middleware or some redirection mechanisms between the app on vercel and the public?
like cloudflare or vercel firewall or something of that sort
im very puzzled because it should work fine but it doesn't. what happens here is that it's treating your /api like a normal page instead of an api route and i don't know why
Avatar
It's the old Next 12 pages router. That's why I am also confused. It has strange folder structure.
Avatar
did it ever work (on vercel) before and only suddenly broke recently?
Avatar
I started working on this issue just yesterday. Haven't worked on this project before.
Anyway, let's leave it there.
Thank you a lot for helping me for a full 40-45 minutes.
Avatar
i think the only sensible explanation here is that vercel has some sort of bugs. i suggest seeking assistance on https://vercel.community, or if you have a paid vercel plan, you can ask directly at https://vercel.com/help.

never seen the pages router api routes being treated as normal pages before, that's not supposed to happen.
Avatar
Got it.
I will try it.