next.js: [NEXT-315] NextJs13 - App Dir - Uncaught Error: NEXT_REDIRECT

Verify canary release

  • 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.

NEXT-315

About this issue

  • Original URL
  • State: closed
  • Created 2 years ago
  • Reactions: 17
  • Comments: 33 (5 by maintainers)

Commits related to this issue

Most upvoted comments

I am using the last version and I am getting: Error: NEXT_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.

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

@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!

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 👍

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.

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.

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.

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?

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”.

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

can someone try?

image

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

Same, the error is happening within an async server component

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

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.