vercel / next.js

The React Framework
https://nextjs.org
MIT License
124.69k stars 26.61k forks source link

Console error "Loading initial props cancelled” after redirecting inside getInitialProps on client side #40554

Closed nietkov closed 19 hours ago

nietkov commented 1 year ago

Verify canary release

Provide environment information

Operating System:
  Platform: linux
  Arch: x64
  Version: #202201092355 SMP PREEMPT Mon Jan 10 00:21:11 UTC 2022
Binaries:
  Node: 16.13.1
  npm: 8.18.0
  Yarn: N/A
  pnpm: N/A
Relevant packages:
  next: 12.3.0
  eslint-config-next: N/A
  react: 18.2.0
  react-dom: 18.2.0

What browser are you using? (if relevant)

No response

How are you deploying your application? (if relevant)

No response

Describe the Bug

I got the console error "Loading initial props canceled” after redirecting inside getInitialProps on the client side

import React from "react";
import Router from "next/router";

const TestPage = () => {
    return <div>Test Page</div>
}

TestPage.getInitialProps = context => {
    const { req, res } = context;
    if (req) {
                res.writeHead(302, { Location: '/other' })
                res.end();
    } else {
        Router.push("/other");
    }
    return {}
}

export default TestPage;

Expected Behavior

Not getting error in console

Link to reproduction

https://codesandbox.io/s/eloquent-thompson-rkn897

To Reproduce

rubytree33 commented 1 year ago

Looking at this.

rubytree33 commented 1 year ago

This seems to be the line where the router cancels itself: https://github.com/vercel/next.js/blob/bbeaf081ae7a6d3c22c5850b39e5672b2c6264f2/packages/next/shared/lib/router/router.ts#L1323 I'm not sure yet what the intended logic is.

rubytree33 commented 1 year ago

@ijjk Is this error supposed to prevent the router from completing navigation? It navigates anyway and then throws after, and I'm not sure if this is intended behavior. Maybe it needs to be caught somewhere?


https://github.com/vercel/next.js/commit/122899bd37c70e12e6ac3d9503931bd0d4ac424b seems to be the change which introduced the error behavior, though according to the description here it seems like this should terminate navigation entirely. Or maybe this is a case that this change didn't account for.

Apparently this is supposed to be a wrapper for getting initial props and is designed to fail when a certain type of navigation occurs (which calls this.clc() above): https://github.com/vercel/next.js/blob/cbfab2a3b732a5be789f0a3a9e4c2e1177adf80e/packages/next/shared/lib/router/router.ts#L2313-L2332

However, by the time we get back to the wrapper's logic, the navigation has already been prepared (and completes after the error is thrown). This is because change continues as normal after calling this.clc().

I'm not sure what needs to be done here since I don't understand the logic in the router.

Ajmaljalal commented 1 year ago

I have the same issue and it was introduced after I added getServerSideProps to my page. I am doing an API call and returning the response:

export const getServerSideProps = async ({ req }) => { const posts = await getAllFeedPosts(req) return { props: { posts } } }

kjellski commented 1 year ago

I'm having the same problem:

I've got a query params-based state that should be changed after a select value was changed. And this error occurs regularly - not all the time though.

I'm navigating to /foo and changing the input, which should set the bar parameter to baz, so we should end up at /foo?bar=baz.

Is anyone working on this already?

pmo022 commented 1 year ago

The same issue happens to us when redirecting user to a login page when we're fetching initial props.

It might be possible to avoid the issue by using router events. The following code example waits until the previous redirect is complete before doing an auth check and redirect with the line of code router.events.on('routeChangeComplete', authCheck).

https://jasonwatmore.com/post/2021/08/30/next-js-redirect-to-login-page-if-unauthenticated

I'm a bit hesitant to rewrite the existing login logic and redirects, so it might take a while before I test if the code linked above solves the issue. I'll post an update when or if I do, but figured it was worth sharing regardless.

coderbaozi commented 1 year ago

I suspect it's the problem with async await syntax sugar, and when I remove async await syntax sugar, the problem is solved

coderbaozi commented 1 year ago

I have the same issue and it was introduced after I added getServerSideProps to my page. I am doing an API call and returning the response:

export const getServerSideProps = async ({ req }) => { const posts = await getAllFeedPosts(req) return { props: { posts } } }

I suspect it's the problem with async await syntax sugar, and when I remove async await syntax sugar, the problem is solved

aretrace commented 1 year ago

I'm having the same problem:

I've got a query params-based state that should be changed after a select value was changed. And this error occurs regularly - not all the time though.

I'm navigating to /foo and changing the input, which should set the bar parameter to baz, so we should end up at /foo?bar=baz.

Is anyone working on this already?

Experiencing the same thing while doing something similar, am using getServerSideProps like @coderbaozi as well.

rdylina commented 1 year ago

Same problem here, seems to be related to auth redirection on my side as well.

leoselig commented 1 year ago

Same happening for me. Also, there is a high chance (if not guarantee) that pageProps is {} although getServerSideProps returns data. Happens to me when:

Jared-Dahlke commented 1 year ago

i'm getting the same error using "next": "^13.4.13",

i have this hook:

import { useSearchParams } from "next/navigation";
import { useRouter } from "next/router";

export const useCustomSearchparams = () => {
  const searchParams = useSearchParams();
  const router = useRouter();

  const workspaceId = searchParams.get("workspaceId");
  const setWorkspaceId = (id: string) => {
    router.push({
      pathname: router.pathname,
      query: { ...router.query, workspaceId: id },
    });
  };

  return {
    workspaceId,
    setWorkspaceId,
  };
};

and i use it in a useEffect like this:

 useEffect(() => {
    if (!workspaceSwid && workspaces.length > 0 && workspaces[0].swid) {
      setWorkspaceId(workspaces[0].swid);
    }
  }, [workspaceSwid, workspaces, setWorkspaceId]);

i get this error:

Error: Loading initial props cancelled
    at eval (router.js:1490:29)
    at async Router.getRouteInfo (router.js:1201:43)
    at async Router.change (router.js:778:29)

any word on this?

ikapta commented 11 months ago

@Jared-Dahlke I encountered the same error. I have a search input that triggers a search event on keydown, but the form onSubmit is also bound to the same search action. As a result, the search action is executed twice, causing Router.replace to be invoked twice and resulting in the error. To resolve this issue, I found two possible solutions. One is to use setTimeout(() => handleSearch(), 300), and the other is to remove the keydown event from the input. Both approaches effectively solved my problem, but I believe it's best to avoid invoking Router.replace more than once.

wisdom-ossai commented 9 months ago

In my own case, I had a check on the home page that uses useSession() hook from next-auth. It checks if the user is authenticated and navigates the user to the dashboard using router.push(). If the user is unauthenticated it equally uses router.push to navigate the user to the login page. I replicated this behavior on the login page as well and didn't remember to remove the condition that routes to the login page (inside the login page itself).

So a possible cause of this issue may be that you are trying to do router.push() to a page you are already on. If that is the case, remove that line and try again.

I hope this helps.

Pratikh commented 3 months ago

please share solution if anyone found it i am facing same issue

Edit by maintainer bot: Comment was automatically minimized because it was considered unhelpful. (If you think this was by mistake, let us know). Please only comment if it adds context to the issue. If you want to express that you have the same problem, use the upvote 👍 on the issue description or subscribe to the issue for updates. Thanks!

vicasas commented 3 months ago

Same problem here. In my case we are using Next.js 12 with router pages with getServerSideProps to make a call to an API of pages/api/ then we page those records into a DataTable, where if I fast forward through the pages it throws the error in the console.

Error: Loading initial props canceled

dsdevries commented 1 day ago

I'm on the latest version of Nextjs 14.2.7 and I'm also getting this error. It's been 2 years now since this ticket is raised. Are there any updates?

This error skews up our metrics in Datadog RUM. It says that over 10% of our sessions encounter this error. When I look at the session replay you see that it is caused by people clicking on a link to a rather slow page and then change their mind or click on the link again. I feel that cancelling a routechange should not throw an uncaught error.