jojo
jojo

Reputation: 11

how to fix next auth sigin error 302 and csrf=true

I installed next-auth in the next 13 and i created a folder api/auth/admin/[...nextauth]/route.ts and api/auth/user/[...nextauth]/route.ts I created two because I have two separate pages for login

the code in the admin route:

import { NextAuthOptions } from "next-auth";
import NextAuth from "next-auth/next";
import CredentialsProvider from "next-auth/providers/credentials";

const authOption: NextAuthOptions = {
    providers: [
        CredentialsProvider({
            name: "Credentials",
            credentials: {
                email: { label: "email", type: "text", placeholder: "jsmith" },
                password: { label: "Password", type: "password" }
            },
            async authorize(credentials, req) {
                const user = { id: "1", name: "J Smith", email: "[email protected]" }
                console.log(credentials?.email);

                if (user) {
                    return user
                } else {
                    return null
                }
            }
        })
    ],
    pages: {
        signIn: '/auth/admin',
        error: '/auth/admin/', // Error code passed in query string as ?error=
    },
    callbacks: {
        async signIn({ user, account, profile, email, credentials }) {
            return true
        },
    }
}
const handler = NextAuth(authOption);

export { handler as GET, handler as POST }

in the user route same above code but the signin page is changed

this is how i trying to signin below is the code:

const csrf = await fetch('/api/auth/admin/csrf');
const { csrfToken } = await csrf.json();

const response = await fetch('/api/auth/admin/signin', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
    'X-CSRF-Token': csrfToken,
  },
  body: JSON.stringify(formData),
  redirect: 'manual'
});

const data = await response.json();

but it goes to the URL then get a 302 fond and redirects to api/auth/signin the the result will be 404 and the URL look like this http://localhost:3000/api/auth/signin?csrf=true

middleware code :

import { NextRequest, NextResponse } from "next/server";
import { getToken } from "next-auth/jwt";
export { default } from "next-auth/middleware"

export const config = { matcher: ["/admin/:path*", "/user/:path*"] }

export async function middleware(request: NextRequest) {
  const token = await getToken({ req: request });
  const url = new URL(request.url);

  if (!token && url.pathname.startsWith('/admin') == true) {
    return NextResponse.rewrite(new URL('/auth/admin', request.url))
  }

  if (!token && url.pathname.startsWith('/user') == true) {
    return NextResponse.rewrite(new URL('/auth/user', request.url))
  }
}

HOW CAN I FIX THIS?

Upvotes: 0

Views: 781

Answers (1)

Greg Bacchus
Greg Bacchus

Reputation: 2476

I had this same problem and isolated it (in my case) to when I was running the project with bunjs.

Initially, I only observed the problem when I was running the "standalone" build, as when you run bun run dev, bun is just the runner - it still uses node as the runtime. But if you run bun -b run dev it will use bun as the runtime and this issue occurs.

Upvotes: 1

Related Questions