Preflight doesn't pass access control check with Auth0 & Nextjs

Ready to post? :mag: First, try searching for your answer.
Anyone getting this error:

Access to fetch at ‘’ (redirected from ‘http://localhost:3000/api/auth/login?_rsc=1wtp7’) from origin ‘http://localhost:3000’ has been blocked by CORS policy: Response to preflight request doesn’t pass access control check: 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.

Been stuck on it for a few days, where I’ve added the following function in Middleware

function handleCors(request: NextRequest, response: NextResponse<unknown>) {
    if (request.nextUrl.pathname.startsWith("/api")) {
      console.log('API request: ', request.nextUrl.pathname)
      response.headers.append('Access-Control-Allow-Credentials', "true")
      response.headers.append('Access-Control-Allow-Origin', '*')
      response.headers.append('Access-Control-Allow-Methods', 'GET,DELETE,PATCH,POST,PUT,OPTIONS')
      response.headers.append(
        'Access-Control-Allow-Headers',
        'X-CSRF-Token, X-Requested-With, Accept, Accept-Version, Content-Length, Content-MD5, Content-Type, Date, X-Api-Version, Content-Type, Authorization, Authorize, RSC, Next-Router-State-Tree, Next-Router-Prefetch, Cache-Control, Same-Origin'
      )
      return response;
    }
}

and done similar patterns via next.config.js and route level too but same error.

1 Like

I had a very similar issue. Following this GitHub issue (CORS Errors on logout) I was able to fix it.

Next.js does something fantastic with prefetching links as it speeds up the UX. However, in this case with Auth0 they have an internal block on this.

From the looks of your issue, you are creating a login button. This will likely be the origin of your problem not your headers. Try switching your Link tag to an a tag.

My original:

import { Button } from "../ui/button";
import Link from "next/link";

export default function LogoutButton({ ...props }) {
  return(
    <Link
      href={"/api/auth/logout"}
      >
      <Button {...props}>
        Logout
      </Button>
    </Link>
  )
}

Fix:

import { Button } from "../ui/button";

export default function LogoutButton({ ...props }) {
  return(
    <a
      href={"/api/auth/logout"}
      >
      <Button {...props}>
        Logout
      </Button>
    </a>
  )
}

I hope this helps, because I know how frustrating it was for me to fix it as well.

2 Likes

Yeahh this was the issue, I ended up switching all my Links for auth0 to Anchors and it started working… a fustrating bug that was hard to debug!

1 Like

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.