next.js icon indicating copy to clipboard operation
next.js copied to clipboard

NextJs13 - App Dir - Uncaught Error: NEXT_REDIRECT

Open schemburkar opened this issue 2 years ago • 4 comments

Verify canary release

  • [X] I verified that the issue exists in the latest Next.js canary release

Provide environment information

Operating System: Platform: win32 Arch: x64 Version: Windows 10 Home Single Language Binaries: Node: 18.5.0 npm: N/A Yarn: N/A pnpm: N/A Relevant packages: next: 13.0.3-canary.0 eslint-config-next: 13.0.2 react: 18.2.0 react-dom: 18.2.0

What browser are you using? (if relevant)

Microsoft Edge Version 109.0.1482.0 (Official build) canary (64-bit)

How are you deploying your application? (if relevant)

yarn dev

Describe the Bug

In /app/(protected)/dashboard/page.tsx, below code fails if it hit the direct url of /dashboard

import { redirect } from "next/navigation";

if (!response.isSignedIn) {
    redirect('/')
  }

Error is as below

client.js:692 
        
Uncaught Error: NEXT_REDIRECT
    at redirect (webpack-internal:///(sc_server)/./node_modules/next/dist/client/components/redirect.js:11:19)
    at dashboard (webpack-internal:///(sc_server)/./app/(protected)/dashboard/page.tsx:9:62)
    at attemptResolveElement (webpack-internal:///(sc_server)/./node_modules/next/dist/compiled/react-server-dom-webpack/server.browser.js:1167:42)
    at resolveModelToJSON (webpack-internal:///(sc_server)/./node_modules/next/dist/compiled/react-server-dom-webpack/server.browser.js:1620:53)
    at Array.toJSON (webpack-internal:///(sc_server)/./node_modules/next/dist/compiled/react-server-dom-webpack/server.browser.js:1081:40)
    at stringify (<anonymous>)
    at processModelChunk (webpack-internal:///(sc_server)/./node_modules/next/dist/compiled/react-server-dom-webpack/server.browser.js:163:36)
    at retryTask (webpack-internal:///(sc_server)/./node_modules/next/dist/compiled/react-server-dom-webpack/server.browser.js:1823:50)
    at performWork (webpack-internal:///(sc_server)/./node_modules/next/dist/compiled/react-server-dom-webpack/server.browser.js:1856:33)
    at AsyncLocalStorage.run (node:async_hooks:330:14)

Full repro can be done using next-create-app and then adding routes in app dir. Attached end-to end zip next13-redirect-demo.zip

Ref: https://github.com/vercel/next.js/issues/42537

Expected Behavior

Redirect should happen without errors in console or developer tools in browser

Link to reproduction

https://github.com/vercel/next.js/files/9947979/next13-redirect-demo.zip

To Reproduce

yarn install
yarn dev

On the browser, directly hit url http://localhost:3000/dashboard with dev tools open for capturing error.

schemburkar avatar Nov 07 '22 03:11 schemburkar

Ah I understand what's going on now, the other issue said that is was functionally broken but it's functioning correctly, just showing an error log. It does redirect, both during yarn dev and yarn build && yarn start.

Getting rid of the error log in the console was on my todo list already, bigger changes to work on first 👍

timneutkens avatar Nov 07 '22 10:11 timneutkens

Thanks @timneutkens! Appreciated. Its not a blocker right now at least.

FYI - for me it redirected to error for yarn build && yarn start but that was on canary-1 version. so it may have started working there now!

schemburkar avatar Nov 07 '22 10:11 schemburkar

Can't wait for this work! Redirecting from a server component is insanely useful. I can't imagine having to run everything through a client component just to redirect (outside of middleware)

Am I right in understanding, this function is currently not finished? It redirects, but currently throws an error and in the future it won't?

oelbaga avatar Nov 08 '22 23:11 oelbaga

Good question and I agree with you @oelbaga, personnaly I use it for check if the authentication token is present, otherwise redirect people, currently at this stage, I commented it, I hope it will be fixed ASAP!

Any progress on this @timneutkens ?

imclint21 avatar Nov 11 '22 18:11 imclint21

Also encountered this issue if I disable JavaScript in the browser to make sure that it's a server-side redirect. When disabled, it redirects to a blank screen, but if I enable JavaScript the redirect works correctly.

codingwithmanny avatar Nov 20 '22 08:11 codingwithmanny

I am getting this issue too, version 13.0.4

danthegoodman1 avatar Nov 23 '22 15:11 danthegoodman1

current workaround is just window.location.replace()

danthegoodman1 avatar Nov 23 '22 15:11 danthegoodman1

I'm running in to this issue as well.

Besides occasional bugs like these, I'm having a blast using the App directory.

Mac MacBook Pro (14-inch, 2021) Apple M1 Max

Node: v16.14.0 npm: 8.19.2

"next": "13.0.5", "react": "18.2.0", "react-dom": "18.2.0",

austinyearlykim avatar Nov 27 '22 00:11 austinyearlykim

Just to double check: on the latest stable it should no longer crash the process and only log in the browser console but still function.

Also encountered this issue if I disable JavaScript in the browser to make sure that it's a server-side redirect.

This is currently expected, handling certain cases of redirect() as server-side redirects is not implemented yet, general recommendation for that right now is using middleware.

current workaround is just window.location.replace()

You shouldn't need any workaround for this. Keep in mind redirect() can only be called as part of rendering and not as part of event handlers like onClick though.

timneutkens avatar Nov 28 '22 10:11 timneutkens

I was using it within a useEffect IIRC

danthegoodman1 avatar Nov 29 '22 01:11 danthegoodman1

This is currently expected, handling certain cases of redirect() as server-side redirects is not implemented yet, general recommendation for that right now is using middleware.

But the demo usage on beta doc should be a server side redirect https://beta.nextjs.org/docs/api-reference/redirect

nikechanhk avatar Dec 06 '22 05:12 nikechanhk

I am using the last version and I am getting: Error: NEXT_REDIRECT

imclint21 avatar Feb 08 '23 12:02 imclint21

With the latest version, this works for me in synchronous components, but throws an error with async server components.

msherer95 avatar Feb 11 '23 21:02 msherer95

Same, the error is happening within an async server component

mklnz avatar Feb 14 '23 17:02 mklnz

me in the RootLayout:

export default function RootLayout ({ children }: LayoutProps) {
	const useCookies = cookies();
	if (!useCookies.has(HypeProxyApiCookieName)) {
		// redirect("/dev/login");
	}

imclint21 avatar Feb 14 '23 17:02 imclint21

for me, the redirect method break on both synchronous and async components

max8hine avatar Feb 15 '23 03:02 max8hine

Strangly when you create a sub-folder like this, the redirection works well:

can someone try?

image

imclint21 avatar Feb 15 '23 13:02 imclint21

I did some tests and what i figure out its that redirect its broken between layouts.

If you have src/app/dash and src/app/auth you can't redirect server-side between then, I actually couldn't redirect using the client side, now I'm just using window.location which is bad.

vine1993 avatar Feb 22 '23 18:02 vine1993

Current workaround is to make the layout a Client Component with use client and use a useEffect, with a router.replace (router coming from useRouter) for redirecting.

Something like that:

'use client'

import { useEffect } from 'react'
import { useRouter } from 'next/navigation'

export type NestedLayoutProps = React.PropsWithChildren

const NestedLayout = (props: NestedLayoutProps): JSX.Element => {
  const { children } = props

  const router = useRouter()

  useEffect(() => {
    // some logic...

    if (/* some condition */) {
      router.replace(`/some/route`)
    }
  }, [])

  return <>{children}</>
}

export default NestedLayout

I find using router.replace a little bit nicer than using window.location, but not a big deal. I consider this as a workaround, and does not strictly what I want, because now the user when they go to the page, there is a "flash" until the client side loads, and the useEffect executes client side. It would be a lot better to fetch data with async Server Components and redirect server side, so for the user it is instant, without "flash".

theoludwig avatar Mar 03 '23 22:03 theoludwig

@Divlo Yes but this doesn't work for sensitive redirects like cookie auth checking. Hope we can get to this soon because it's pretty core to any product and was my first move in trying out the app dir!

pistachiomatt avatar Mar 05 '23 21:03 pistachiomatt

13.2.4-canary.4

I also cannot use next/navigation's redirect() to redirect from a Layout server component in app directory to a Next.js 12 client component inside the pages directory.

image

pfista avatar Mar 06 '23 23:03 pfista

Same problem here, nextjs throwing error when i redirect from: (auth)/login/page.tsx -> redirect function in -> (auth)/layout.tsx to (app)/page.tsx

So i am basically trying to redirect from /login to /

mpiorowski avatar Mar 07 '23 07:03 mpiorowski

same problem here

devitcf avatar Mar 07 '23 08:03 devitcf

EDIT: Solved. In my case it was a <meta name="description" content="somestring"/> tag. Content source was being obtained through a function call, and that function was throwing an uncaught error and preventing the rest of the page being rendered

==========

I am using v13.1.4 and getting different errors but I think they can be related to this issue

index.js?8267:10 Uncaught TypeError: Cannot read properties of null (reading 'type')
    at releaseResource (webpack-internal:///(app-client)/./node_modules/next/dist/compiled/react-dom/cjs/react-dom.development.js:12173:20)
    at commitMutationEffectsOnFiber (webpack-internal:///(app-client)/./node_modules/next/dist/compiled/react-dom/cjs/react-dom.development.js:28033:17)
    at recursivelyTraverseMutationEffects (webpack-internal:///(app-client)/./node_modules/next/dist/compiled/react-dom/cjs/react-dom.development.js:27935:7)
    at commitMutationEffectsOnFiber (webpack-internal:///(app-client)/./node_modules/next/dist/compiled/react-dom/cjs/react-dom.development.js:28327:9)
    at recursivelyTraverseMutationEffects (webpack-internal:///(app-client)/./node_modules/next/dist/compiled/react-dom/cjs/react-dom.development.js:27935:7)
    at commitMutationEffectsOnFiber (webpack-internal:///(app-client)/./node_modules/next/dist/compiled/react-dom/cjs/react-dom.development.js:28327:9)
    at recursivelyTraverseMutationEffects (webpack-internal:///(app-client)/./node_modules/next/dist/compiled/react-dom/cjs/react-dom.development.js:27935:7)
    at commitMutationEffectsOnFiber (webpack-internal:///(app-client)/./node_modules/next/dist/compiled/react-dom/cjs/react-dom.development.js:27994:9)
    at recursivelyTraverseMutationEffects (webpack-internal:///(app-client)/./node_modules/next/dist/compiled/react-dom/cjs/react-dom.development.js:27935:7)
    at commitMutationEffectsOnFiber (webpack-internal:///(app-client)/./node_modules/next/dist/compiled/react-dom/cjs/react-dom.development.js:27955:9)
    at recursivelyTraverseMutationEffects (webpack-internal:///(app-client)/./node_modules/next/dist/compiled/react-dom/cjs/react-dom.development.js:27935:7)
    at commitMutationEffectsOnFiber (webpack-internal:///(app-client)/./node_modules/next/dist/compiled/react-dom/cjs/react-dom.development.js:28327:9)
    at recursivelyTraverseMutationEffects (webpack-internal:///(app-client)/./node_modules/next/dist/compiled/react-dom/cjs/react-dom.development.js:27935:7)
    at commitMutationEffectsOnFiber (webpack-internal:///(app-client)/./node_modules/next/dist/compiled/react-dom/cjs/react-dom.development.js:28327:9)
    at recursivelyTraverseMutationEffects (webpack-internal:///(app-client)/./node_modules/next/dist/compiled/react-dom/cjs/react-dom.development.js:27935:7)
    at commitMutationEffectsOnFiber (webpack-internal:///(app-client)/./node_modules/next/dist/compiled/react-dom/cjs/react-dom.development.js:28327:9)
    at recursivelyTraverseMutationEffects (webpack-internal:///(app-client)/./node_modules/next/dist/compiled/react-dom/cjs/react-dom.development.js:27935:7)
    at commitMutationEffectsOnFiber (webpack-internal:///(app-client)/./node_modules/next/dist/compiled/react-dom/cjs/react-dom.development.js:28327:9)
    at recursivelyTraverseMutationEffects (webpack-internal:///(app-client)/./node_modules/next/dist/compiled/react-dom/cjs/react-dom.development.js:27935:7)
    at commitMutationEffectsOnFiber (webpack-internal:///(app-client)/./node_modules/next/dist/compiled/react-dom/cjs/react-dom.development.js:28327:9)
    at recursivelyTraverseMutationEffects (webpack-internal:///(app-client)/./node_modules/next/dist/compiled/react-dom/cjs/react-dom.development.js:27935:7)
    at commitMutationEffectsOnFiber (webpack-internal:///(app-client)/./node_modules/next/dist/compiled/react-dom/cjs/react-dom.development.js:27955:9)
    at recursivelyTraverseMutationEffects (webpack-internal:///(app-client)/./node_modules/next/dist/compiled/react-dom/cjs/react-dom.development.js:27935:7)
    at commitMutationEffectsOnFiber (webpack-internal:///(app-client)/./node_modules/next/dist/compiled/react-dom/cjs/react-dom.development.js:27994:9)
    at recursivelyTraverseMutationEffects (webpack-internal:///(app-client)/./node_modules/next/dist/compiled/react-dom/cjs/react-dom.development.js:27935:7)
    at commitMutationEffectsOnFiber (webpack-internal:///(app-client)/./node_modules/next/dist/compiled/react-dom/cjs/react-dom.development.js:27955:9)
    at recursivelyTraverseMutationEffects (webpack-internal:///(app-client)/./node_modules/next/dist/compiled/react-dom/cjs/react-dom.development.js:27935:7)
    at commitMutationEffectsOnFiber (webpack-internal:///(app-client)/./node_modules/next/dist/compiled/react-dom/cjs/react-dom.development.js:27955:9)
    at recursivelyTraverseMutationEffects (webpack-internal:///(app-client)/./node_modules/next/dist/compiled/react-dom/cjs/react-dom.development.js:27935:7)
    at commitMutationEffectsOnFiber (webpack-internal:///(app-client)/./node_modules/next/dist/compiled/react-dom/cjs/react-dom.development.js:27955:9)
    at recursivelyTraverseMutationEffects (webpack-internal:///(app-client)/./node_modules/next/dist/compiled/react-dom/cjs/react-dom.development.js:27935:7)
    at commitMutationEffectsOnFiber (webpack-internal:///(app-client)/./node_modules/next/dist/compiled/react-dom/cjs/react-dom.development.js:27955:9)
    at recursivelyTraverseMutationEffects (webpack-internal:///(app-client)/./node_modules/next/dist/compiled/react-dom/cjs/react-dom.development.js:27935:7)
    at commitMutationEffectsOnFiber (webpack-internal:///(app-client)/./node_modules/next/dist/compiled/react-dom/cjs/react-dom.development.js:27955:9)
    at recursivelyTraverseMutationEffects (webpack-internal:///(app-client)/./node_modules/next/dist/compiled/react-dom/cjs/react-dom.development.js:27935:7)
    at commitMutationEffectsOnFiber (webpack-internal:///(app-client)/./node_modules/next/dist/compiled/react-dom/cjs/react-dom.development.js:28327:9)
    at recursivelyTraverseMutationEffects (webpack-internal:///(app-client)/./node_modules/next/dist/compiled/react-dom/cjs/react-dom.development.js:27935:7)
    at commitMutationEffectsOnFiber (webpack-internal:///(app-client)/./node_modules/next/dist/compiled/react-dom/cjs/react-dom.development.js:28327:9)
    at recursivelyTraverseMutationEffects (webpack-internal:///(app-client)/./node_modules/next/dist/compiled/react-dom/cjs/react-dom.development.js:27935:7)
    at commitMutationEffectsOnFiber (webpack-internal:///(app-client)/./node_modules/next/dist/compiled/react-dom/cjs/react-dom.development.js:28151:9)
    at commitMutationEffects (webpack-internal:///(app-client)/./node_modules/next/dist/compiled/react-dom/cjs/react-dom.development.js:27905:3)
    at commitRootImpl (webpack-internal:///(app-client)/./node_modules/next/dist/compiled/react-dom/cjs/react-dom.development.js:31458:5)
    at commitRoot (webpack-internal:///(app-client)/./node_modules/next/dist/compiled/react-dom/cjs/react-dom.development.js:31325:5)
    at finishConcurrentRender (webpack-internal:///(app-client)/./node_modules/next/dist/compiled/react-dom/cjs/react-dom.development.js:30258:9)
    at performConcurrentWorkOnRoot (webpack-internal:///(app-client)/./node_modules/next/dist/compiled/react-dom/cjs/react-dom.development.js:30050:7)
    at workLoop (webpack-internal:///(app-client)/./node_modules/next/dist/compiled/scheduler/index.js:11:3897)
    at flushWork (webpack-internal:///(app-client)/./node_modules/next/dist/compiled/scheduler/index.js:11:3606)
    at MessagePort.performWorkUntilDeadline (webpack-internal:///(app-client)/./node_modules/next/dist/compiled/scheduler/index.js:11:1787)
Uncaught Error: Should not already be working.
    at performConcurrentWorkOnRoot (webpack-internal:///(app-client)/./node_modules/next/dist/compiled/react-dom/cjs/react-dom.development.js:29943:11)
    at workLoop (webpack-internal:///(app-client)/./node_modules/next/dist/compiled/scheduler/index.js:11:3897)
    at flushWork (webpack-internal:///(app-client)/./node_modules/next/dist/compiled/scheduler/index.js:11:3606)
    at MessagePort.performWorkUntilDeadline (webpack-internal:///(app-client)/./node_modules/next/dist/compiled/scheduler/index.js:11:1787)

Code that causes redirect error:

const Layout = async ({children, params}: LayoutPagesProps) => {
    if (!(await getVerifiedTokenParsedFromCookie()).purposes?.includes(CREATOR_PURPOSE)) {
        redirect(`/${params.locale}/login`);
    }
    return <>{children}</>;
};

export default Layout;

But it happens even when I try to use router.push to navigate to login route.

jalaguerom avatar Mar 07 '23 17:03 jalaguerom

error - node_modules/next/dist/client/components/redirect.js (11:18) @ redirect
error - unhandledRejection: Error: NEXT_REDIRECT

FWIW, I'm seeing the same error on NextJS 13.2.4, but only if I await a Promise.

Works

function requireAuth() {
  const cookieStore = cookies()
  const sessionCookie = cookieStore.get(SESSION_COOKIE_NAME)
  if (!sessionCookie) {
    return redirect("/login")
  }
  return authenticate(sessionCookie.value)
}

Does Not Work

function requireAuth() {
  const cookieStore = cookies()
  const sessionCookie = cookieStore.get(SESSION_COOKIE_NAME)
  if (!sessionCookie) {
    return redirect("/login")
  }
  const { user } = await authenticate(sessionCookie.value) // await here causes error
  return user
}

Clee681 avatar Mar 11 '23 21:03 Clee681

export default async function AuthLayout({ children }: AuthLayoutProps) {
  const supabase = createServerClient()

  const {
    data: { session },
  } = await supabase.auth.getSession()

  if (session) {
    redirect("/dashboard")
  }

  return <>{children}</>
}

next dev It working well next build && next start It will throw Error NEXT_REDIRECT

image

Browser log in production

image

Sentry error in production

Can anyone provide guidance on how to resolve this? Thank you.

kamtorocks avatar Mar 12 '23 16:03 kamtorocks

Strangly when you create a sub-folder like this, the redirection works well:

can someone try?

image

GUYS PLEASE TEST THIS, I think it explain all

imclint21 avatar Mar 12 '23 20:03 imclint21

Strangly when you create a sub-folder like this, the redirection works well: can someone try? image

GUYS PLEASE TEST THIS, I think it explain all

I really don't understand what you're trying to demonstrate here

prmichaelsen avatar Mar 14 '23 03:03 prmichaelsen

I was getting this error when deployed on vercel, but not locally (even when using vercel dev).

After importing server-only, the redirect error OP has is gone, but now the error is:

Error: An error occurred in the Server Components render. The specific message is omitted in production builds to avoid leaking sensitive details. A digest property is included on this error instance which may provide additional details about the nature of the error.

I have my /app directory page set up in a way where I don't want the actual /app route to be anything - so redirecting to the /app/dashboard route as follows:

import 'server-only'
import { redirect } from 'next/navigation'

export default function App() {
  redirect('/app/dashboard')
}

Any ideas?

Edit: The redirect actually works fine btw, just want to clear any errors of course!

shanehoban avatar Mar 14 '23 21:03 shanehoban

Strangly when you create a sub-folder like this, the redirection works well: can someone try? image

GUYS PLEASE TEST THIS, I think it explain all

I really don't understand what you're trying to demonstrate here

When you use multiple root layouts like this: https://beta.nextjs.org/docs/routing/defining-routes#example-creating-multiple-root-layouts

the problem does not happen

imclint21 avatar Mar 15 '23 19:03 imclint21