Next.js Discord

Discord Forum

NEXT_REDIRECT error while signing in

Answered
Spotted Rail posted this in #help-forum
Open in Discord
Spotted RailOP
Authentication error: Error: NEXT_REDIRECT at l (/var/task/.next/server/chunks/381.js:2:5754) at c (/var/task/.next/server/chunks/381.js:2:5969) at i1 (/var/task/.next/server/chunks/381.js:390:55565) at async K (/var/task/.next/server/chunks/416.js:1:12557) at async /var/task/node_modules/next/dist/compiled/next-server/app-page.runtime.prod.js:16:418 at async rE (/var/task/node_modules/next/dist/compiled/next-server/app-page.runtime.prod.js:15:7978) at async r7 (/var/task/node_modules/next/dist/compiled/next-server/app-page.runtime.prod.js:18:1144) at async es (/var/task/node_modules/next/dist/compiled/next-server/server.runtime.prod.js:16:25916) at async en.responseCache.get.routeKind (/var/task/node_modules/next/dist/compiled/next-server/server.runtime.prod.js:17:1026) at async r6.renderToResponseWithComponentsImpl (/var/task/node_modules/next/dist/compiled/next-server/server.runtime.prod.js:17:508) { digest: 'NEXT_REDIRECT;replace;https://mandarin-mastery.vercel.app/signin;303;', mutableCookies: f { _parsed: Map(2) { '__Secure-authjs.callback-url' => [Object], '__Secure-authjs.session-token' => [Object] },
Answered by Spotted Rail
@B33fb0n3 @riský
Downgrading to these versions solved my issue of redirection after signing in. I didn't have to setup any redirections other than the middleware.
"next": "14.0.1", "next-auth": "^5.0.0-beta.3",

Edit: I also added redirect, and redirectTo option (which is called in server action), it doesn't throw any error in vercel as well.
await signIn('credentials', { email, password, redirect: true, redirectTo: "/dashboard" });
View full answer

62 Replies

Spotted RailOP
_headers: Headers { 'set-cookie': '__Secure-authjs.callback-url=https%3A%2F%2Fmandarin-mastery.vercel.app%2Fsignin; Path=/, __Secure-authjs.session-token=eyJhbGciOiJkaXIiLCJlbmMiOiJBMjU2Q0JDLUhTNTEyIiwia2lkIjoiMWpNNmdaUnB1NzQzMUY0OVo0N2NoQTJHRHdnLXlPNDBTOEI2OGtoRUxwWkpuM3hBTnFVSlRGalZOdnB2NV9RNkpLVnVTZHVlckpjTzlIUGJGeG51LXcifQ..YL4QMlQdSkF7X43gJP-mGA.uIATuZO_rhxnozogOqFGxl6lJjL2y8-4g0vuqvyRtjxcZ1vcgkgD4ddbon0hfz3nWVurMgX_Gzhvv1oSAI1PCOiMEoVV1MWF4GBFOY6zf9660YniYOQrO3Wu9UbdNuS9fl8Fxo2SXaaWwg5btBr6Oq5CYqdNy4-sRJTHXFadCRq8yWnWLaTPy93RVnXXgSmQYD1L8fM-EnP7NjRpT4TT13VKJnsmt3Ey6QaInWywj-fQiIUyRCLF0Ae_eRQWpL9MvoXIHAHX_mcfiZjgFEqveRpcRfbXDAsVKPiw1nL-LzY7KQgTaqKnotvX72GSq3_iX9aO3lsVmBAEF29hpd07937FkglyS8YBKhDaUipICzuntBSyiYo9y-2H1GRtlUq0neg0P7R57OsL9QWT82iFG1lBegBUPSH-MW5pxe0-7gp8FRtmPjGqZ8VdC3YaeIX4egUsMX_SA4GRbFPvRf_EN02m5ypIcNln3armSs_ef5cJHp-EugUqkiZK0xwH0SBTbZS7HCHA_DkfETst_Z83qDPQBfLrcpXIW24zLvmsJ9sEWyzGRvry7LKnlo1FJJ6bPNCk_cYcGwLwnO4XD5wNUaCt2Pm0gY6cEYSU7DPVrhk.F6RSCGeXHtBm0a3o7SoxdU5uVUhmklIe-pTGetcHHPA; Path=/; Expires=Tue, 24 Dec 2024 17:20:30 GMT; Secure; HttpOnly; SameSite=lax' } } }
action.js
export async function authenticate(prevState, formData) {
  try {
    const { email, password } = formData;
    await signIn('credentials', { email, password, redirect: true, callbackUrl: '/dashboard' });
  } catch (error) {
    if (error instanceof AuthError) {
      switch (error.type) {
        case 'CredentialsSignin':
          if (error.code === "Email not verified") {
            return error.code;
          }
          return 'Invalid credentials.';
        default:
          return 'Something went wrong.';
      }
    }
    console.error('Authentication error:', error);
    throw error;
  }
}
@Spotted Rail This error is only received on production (vercel), the localhost works fine
have you set the correct NEXT_AUTH_... url (env variable)?
@B33fb0n3 have you set the correct NEXT_AUTH_... url (env variable)?
Spotted RailOP
Yes I have
@B33fb0n3 have you set the correct NEXT_AUTH_... url (env variable)?
Spotted RailOP
It just has to be my domain right
@Spotted Rail It just has to be my domain right
yea, it need to be a full qualified URL like this: https://www.google.com/. Having just google.com wouldn't work
can you share the authOptions and there the credentials provider with the callbacks: session, jwt & user?
auth.js
middleware.js
import { NextResponse } from "next/server";
import { authMiddleware } from "./auth-edge"; // Path to your edge-compatible auth
import {
    authRoutes,
    DEFAULT_REDIRECT_LOGIN_URL,
    DEFAULT_REDIRECT_HOME_URL,
} from "./routes";

export default async function middleware(req) {
    const { isAuthenticated } = await authMiddleware(req);
    const url = req.nextUrl;
    const route = req.nextUrl.pathname;

    // Redirect logged-in users away from auth pages
    if (authRoutes.some((authRoute) => route.startsWith(authRoute))) {
        if (isAuthenticated) {
            return NextResponse.redirect(new URL(DEFAULT_REDIRECT_HOME_URL, url));
        }
        return NextResponse.next();
    }

    // Protect routes except public pages
    if (!(route === "/" || route === "/signin" || route === "/signup")) {
        if (!isAuthenticated) {
            return NextResponse.redirect(new URL(DEFAULT_REDIRECT_LOGIN_URL, url));
        }
    }

    return NextResponse.next();
}

export const config = {
    matcher: ["/((?!api|_next/static|_next/image|.*\\.png$).*)"],
};
@Spotted Rail auth.js
thanks for sharing! Can you remove this part for a moment to see if there's the issue: (see attached: everything inside the box)
@B33fb0n3 thanks for sharing! Can you remove this part for a moment to see if there's the issue: (see attached: everything inside the box)
Spotted RailOP
This cookies config wasn't there before, and even then I got the same error that I shared above. This was suggested by ai so tried it.
@B33fb0n3 what about the trustHost?
Spotted RailOP
yep that as well
@B33fb0n3 could there be a problem with middleware?
maybe yea.. right now we looking where the specific error comes from. Could you remove this code for a moment to see if the error comes from the middleware:
Spotted RailOP
alright let me try that
@Spotted Rail alright let me try that
Spotted RailOP
still the same error
@B33fb0n3
Spotted RailOP
Update: After adding redirect: false in the signIn call it works.
export async function authenticate(prevState, formData) {
  try {
    const { email, password } = formData;
    await signIn('credentials', { email, password, redirect: false });
  } catch (error) {
    if (error instanceof AuthError) {
      switch (error.type) {
        case 'CredentialsSignin':
          if (error.code === "Email not verified") {
            return error.code;
          }
          return 'Invalid credentials.';
        default:
          return 'Something went wrong.';
      }
    }
    console.error('Authentication error:', error);
    throw error;
  }
}
Spotted RailOP
I keep getting this error in the browser console
Cookie “__vercel_live_token” has been rejected because it is in a cross-site context and its “SameSite” is “Lax” or “Strict”.
But no errors on server logs
Try the redirect like this:
        const signInResult = await signIn("credentials", {
            ...
        });

        if (signInResult.ok) {
            if (window.location.href === signInResult.url) {
                if (callbackUrl?.length > 0) {
                    router.refresh();
                    router.push(callbackUrl);
                }
            } else {
                router.push(signInResult.url)
            }
        } else {
            e.target.password.value = "";
            handleError(signInResult.error)
        }
Spotted RailOP
If I remm correctly, signIn() returns a url. So signInResult would be a string with a url
@Spotted Rail If I remm correctly, signIn() returns a url. So `signInResult` would be a string with a url
The signIn should be an response for the sign in request. Can you verify that?
@B33fb0n3 yes and the error persists, right?
Spotted RailOP
No, before When I tried to login the authentication always failed. So after entering correct credentials if I would manually enter the "/dashboard" url it would redirect back to signin page
@B33fb0n3 The signIn should be an response for the sign in request. Can you verify that?
Spotted RailOP
Sure let me try it out
ahhh then that's the error. The signIn method is a client method. Use it inside your client component
@B33fb0n3 ahhh then that's the error. The signIn method is a client method. Use it inside your client component
Spotted RailOP
Sorry but i Don't understand, this exact way worked in my previous project where i used signin in the server action
@B33fb0n3 ahhh then that's the error. The signIn method is a client method. Use it inside your client component
Spotted RailOP
alright
but just to remind you, my code is working fine in the dev server (localhost), the issue only persists on vercel
@B33fb0n3 try it without the server action
Spotted RailOP
where should the signin imported from
@Spotted Rail where should the signin imported from
should be the same import like before
Spotted RailOP
it's from my auth.js file
@Spotted Rail it's from my auth.js file
from there:
@B33fb0n3 from there:
Spotted RailOP
@B33fb0n3 I tried with this, but as usual it works fine on the localhost but not on vercel
I haven't got any errors on the logs, neither server nor client side
Only the following error remained consistent on the browser console. This shows as soon as the page is rendered.
Cookie “__vercel_live_token” has been rejected because it is in a cross-site context and its “SameSite” is “Lax” or “Strict”.
@Spotted Rail change the options of your cookies to
{
        httpOnly: true,
        sameSite: 'none',
        secure: true
}
@Spotted Rail What's the callbackUrl here?
The url where the user comes from to redirect him back to it after the signin process is done
Spotted RailOP
Why is this thing so broken, it doesn't work as expected
@Spotted Rail this does nothing : (
well.. I guess I run out of options. I heard a lot, that auth.js is many times broken and nobody knows why. The same happens to nextauth beta. I recommend you to switch to nextauth@latest. There everything works like expected (at least I never had problems with that). Btw: auth.js comes from nextauth. So you need to change nearly nothing if you want to switch 👍
@Spotted Rail I'm using `"next-auth": "^5.0.0-beta.18",`
The same happens to nextauth beta
i didnt read whole thread, but if you are try catching, you may be catching the redirect() function from nextjs (it works by throwing NEXT_REDIRECT error)
Spotted RailOP
@B33fb0n3 @riský
Downgrading to these versions solved my issue of redirection after signing in. I didn't have to setup any redirections other than the middleware.
"next": "14.0.1", "next-auth": "^5.0.0-beta.3",

Edit: I also added redirect, and redirectTo option (which is called in server action), it doesn't throw any error in vercel as well.
await signIn('credentials', { email, password, redirect: true, redirectTo: "/dashboard" });
Answer