From f9b1a417fcebe1f90a9c843be1cb32bb754e55ba Mon Sep 17 00:00:00 2001 From: andresgutgon Date: Sat, 25 May 2024 13:57:18 +0200 Subject: [PATCH] Fix NextAuth redirecting to /undefined when signIn method throws an error @auth/core `Auth` function can return an internalResponse or a Standard Response. Internal response has a `redirect` attribute. The problem is that the logic inside `Auth` method when there is an error is returning a Standard web Response which doesn't have `redirect` attribute but we can get redirecting url by using `headers.get('Origin')`. I think this fix this issue: https://github.com/nextauthjs/next-auth/issues/11008 --- docs/pages/guides/pages/signin.mdx | 16 ++- docs/pages/reference/_meta.js | 1 + packages/adapter-test/README.md | 25 +++++ packages/adapter-test/package.json | 44 +++++++++ packages/adapter-test/src/index.ts | 110 +++++++++++++++++++++ packages/adapter-test/tsconfig.json | 9 ++ packages/adapter-test/typedoc.config.cjs | 14 +++ packages/core/src/index.ts | 4 +- packages/next-auth/package.json | 2 + packages/next-auth/src/lib/actions.test.ts | 109 ++++++++++++++++++++ packages/next-auth/src/lib/actions.ts | 10 +- pnpm-lock.yaml | 9 ++ 12 files changed, 347 insertions(+), 6 deletions(-) create mode 100644 packages/adapter-test/README.md create mode 100644 packages/adapter-test/package.json create mode 100644 packages/adapter-test/src/index.ts create mode 100644 packages/adapter-test/tsconfig.json create mode 100644 packages/adapter-test/typedoc.config.cjs create mode 100644 packages/next-auth/src/lib/actions.test.ts diff --git a/docs/pages/guides/pages/signin.mdx b/docs/pages/guides/pages/signin.mdx index 96e6113f1a..644ec9feb9 100644 --- a/docs/pages/guides/pages/signin.mdx +++ b/docs/pages/guides/pages/signin.mdx @@ -99,6 +99,7 @@ We can now build our own custom sign in page. ```tsx filename="app/signin/page.tsx" /providerMap/ import { signIn, auth, providerMap } from "@/auth.ts" +import { AuthError } from 'next-auth' export default async function SignInPage() { return ( @@ -107,7 +108,20 @@ export default async function SignInPage() {
{ "use server" - await signIn(provider.id) + try { + await signIn(provider.id) + } catch (error) { + // Signin can fail for a number of reasons, such as the user + // not existing, or the user not having the correct role. + // In some cases, you may want to redirect to a custom error + if (error instanceof AuthError) { + return redirect(`${SIGNIN_ERROR_URL}?error=${error.type}`) + } + + // Otherwise if a redirects happens NextJS can handle it + // so you can just re-thrown the error and let NextJS handle it. + throw error + } }} >