Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Navigation issue with Browser Back Button Click #7091

Closed
ninjawhocodes opened this issue Apr 20, 2019 · 49 comments
Closed

Navigation issue with Browser Back Button Click #7091

ninjawhocodes opened this issue Apr 20, 2019 · 49 comments
Assignees

Comments

@ninjawhocodes
Copy link

Issue :

  1. From http://localhost:3000 navigate to http://localhost:3000/p/hello using Link.
  2. Refresh the page.
  3. Click back button : It goes to http://localhost:3000 but still renders the content of http://localhost:3000/p/hello it is not loading the content of http://localhost:3000.

I am using "next": "^8.1.0".

@nblthree
Copy link
Contributor

@ninjawhocodes I can't reproduce the problem, can you post a reproduction repo and the version of your browser

@timneutkens
Copy link
Member

Thanks @MarchWorks

@ninjawhocodes
Copy link
Author

https://github.com/ninjawhocodes/react-with-next

I have upload the code on above repo.

Steps to reproduce the issue :

  1. npm install.
  2. npm run dev.
  3. Once page is up click on "here".
    4 . You will be on "http://localhost:3000/p/hello"
  4. Do a refresh from browser.
    6 Click browser back button.
  5. It will go back to "http://localhost:3000" but it will still show the content of "http://localhost:3000/p/hello".

image

image

Aftet Clicking Back
image

@ninjawhocodes
Copy link
Author

@ninjawhocodes I can't reproduce the problem, can you post a reproduction repo and the version of your browser

#7091 (comment)
I have uploaded the code on above and sharing the details in below in fresh comment. Please suggest if this issue can be fixed by doing some workaround.

@nblthree
Copy link
Contributor

nblthree commented Apr 23, 2019

@timneutkens there is an issue caused by importing css files. I will open a new issue with what I found

@ninjawhocodes
Copy link
Author

@timneutkens there is an issue caused by importing css files. I will open a new issue with what I found

okay so for time being could you please suggest a workaround ?

@nblthree
Copy link
Contributor

nblthree commented Apr 23, 2019

@ninjawhocodes use styled-jsx https://github.com/zeit/next.js#built-in-css-support
or import an empty css file or even the same file that you have imported in your index page in all your pages

@nblthree
Copy link
Contributor

@ninjawhocodes personally I will recommend you to use styled-jsx but if you want to use css file then make sure that you are importing one in every page it can be the same or a different one it doesn't matter

@ninjawhocodes
Copy link
Author

@ninjawhocodes personally I will recommend you to use styled-jsx but if you want to use css file then make sure that you are importing one in every page it can be the same or a different one it doesn't matter

Yeah, I have to add style.css for each page then only it will work.

@nblthree
Copy link
Contributor

nblthree commented Apr 23, 2019

@ninjawhocodes you should also know that if you import b.css in b.js and a.css in a.js and you go from a.js page to b.js page you will have a.css loaded in b.js too

@iMerica
Copy link

iMerica commented Jan 8, 2020

New distinct issue that occurs even without a page refresh: #9989

@zachwhitedev
Copy link

zachwhitedev commented Mar 1, 2020

Every time I hit the back button on mobile the site I'm working on loads the page for a second but then the whole page goes blank, and I get the message "An unexpected error occurred."

Screen Shot 2020-02-29 at 10 59 00 PM

Only happens in mobile (on both Chrome and Safari) but not on desktop.

My code:

Screen Shot 2020-02-29 at 11 01 20 PM

To reproduce it you just visit the site on mobile and then hit the back button on your browser.

@stikler51
Copy link

@zachwhitedev I have the same problem. Do you find some solution?

@chiqui3d
Copy link

The same thing happens to me in production and development, the second I return to the home page, I put an error capture:

Shit Markdown

I see this is closed, I have to reopen a new issue?

@chiqui3d
Copy link

chiqui3d commented Jul 23, 2020

I have also added shallow to the Link component, as in this example, and the error still appears:

<Link as={`/blog/${post.slug}`} href="/blog/[slug]" shallow={true}>

@collegewap
Copy link

I have a similar issue:

#9989 (comment)

@JStein92
Copy link

@timneutkens Any update on this? This is a pretty massive issue. Is there an open issue to follow here at least?

@Skarian
Copy link

Skarian commented Aug 22, 2020

@timneutkens Any update here?

@timkindberg
Copy link

timkindberg commented Sep 5, 2020

I have this issue navigating between two static pages. I have to click back twice.

  1. Start on /home
  2. Click /work_orders, navigates properly to Work Orders
  3. Back Button once, see tab title change to "Home" but page content stays as Work Orders content
  4. Back Button again, see URL and page content change back to Home content

We use a mix of:

  • CSS-in-JS (via Chakra-UI)
  • CSS Module imports (aka import styles from './SomeStyles.module.scss')
  • Global CSS imports for legacy components in _app.js

Not sure how CSS is causing the issue but wanted to share what we do.

I've tried on both v9.4.0 and v9.5.3-canary.27 and v9.5.3

@tomlagier
Copy link

tomlagier commented Sep 8, 2020

We're seeing this issue too - navigating forward works OK but navigating backwards doesn't work.

Tested with Next version 9.5.1 and 9.5.3

Also using Chakra, as well as global CSS import.

Link (from /reports/individual, a very large page):

<Link href="/schedule-appointment">{...}</Link>

Clicking the link once takes me to /schedule-appointment, as expected.

/schedule-appointment:

import React, { useEffect } from "react";
import { string } from "prop-types";
import { getUserFromCtx } from "../utils/auth";

function Appointment({ email }) {
  // Embed Calendly inline widget
  useEffect(function addCalendly() {
    const head = document.querySelector("head");
    const script = document.createElement("script");
    script.setAttribute(
      "src",
      "https://assets.calendly.com/assets/external/widget.js"
    );
    head.appendChild(script);
  }, []); // second param causes this to only run once

  const calendlyLink = "...";
  return (
    <div>
      <div id="schedule_form">
        <div
          className="calendly-inline-widget"
          data-url={calendlyLink + "?email=" + email}
          style={{ minWidth: "320px", height: "580px" }}
        />
      </div>
    </div>
  );
}

Appointment.propTypes = {
  email: string.isRequired,
};

export async function getServerSideProps(context) {
  const user = await getUserFromCtx(context);

  // TODO: once calendly adds "Extra Guests" prefill,
  // prefill the extra guests field with all the emails
  // associated with a user's Account
  return {
    props: {
      email: user.user.email,
    },
  };
}

export default Appointment;

Clicking the browser back button from schedule-appointment updates the route in the URL bar to /reports/individual but does not load /reports/individual's content.

Even weirder, if I click back twice (taking me to the page before I clicked the link, in this case /signin), it renders OK, then if I click forward once, I get the /schedule-appointment content rendered in /reports/individual!

If I refresh the page, I get the content for /reports/individual rendered as I expect.

Does anyone know if there's a workaround, even if it forces a hard reload of the page?

After some further investigation, I think this is caused by having a hash in the URL when navigating back. If I remove the hash, the navigation works correctly.

@ijjk
Copy link
Member

ijjk commented Sep 8, 2020

Hi, it sounds like some of the follow-up comments here might be related to #7395 which was resolved in #16477 and is available in the latest version of Next.js v9.5.3

@Spirik
Copy link

Spirik commented Sep 15, 2020

Upgraded to 9.5.3. Still reproduces for me. Hitting browser's back button results in URL in address bar update, but content on the page remains the same.

@ijjk
Copy link
Member

ijjk commented Sep 16, 2020

@Spirik can you provide a repo with a reproduction where this is occurring for you?

@idoshamun
Copy link

I have the same issue. Tried to update to 9.5.3 but it didn't help.
I don't use shallow links but I do have getServerSideProps.

@Spirik
Copy link

Spirik commented Sep 21, 2020

Will try to recreate the issue with clean install, but not sure, when I'll be able to. The only significant difference with my current setup from clean install is that I don't use CSS modules. And occasionally, I use HOCs with getInitialProps.

@aberba
Copy link

aberba commented Sep 23, 2020

@chiqui3d were you able to resolve the back button showing expected error issue? This same problem is killing me here

@shambu2k
Copy link

Hi, it sounds like some of the follow-up comments here might be related to #7395 which was resolved in #16477 and is available in the latest version of Next.js v9.5.3

You meant the canary version?
I tried that, I still have the same issue

@chiqui3d
Copy link

chiqui3d commented Sep 23, 2020

@aberba Supposedly it is fixed in the canary version. But I haven't tried it, as what it's doing was for a static website, what I did was to replace the Link component with "a" tag to prevent it, this is only a temporary solution for static pages.

@timkindberg
Copy link

UPDATE. The issue is fixed for me. It was a bug on our end. We were using history.pushState:

The issue was that the page being navigated to was immediately using history.pushState to alter the URL, resulting in a double entry in the history stack for the destination page.

The page displays a list of items and has filters, so we have code to keep the URL in sync with the filters that the user selects. Well, apparently when the page first loads we did a pushState even when the filters weren't different from the URL.

So please double-check the page you are navigating to and be sure you aren't manipulating the history with pushState. This can also happen with router.push().

@aberba
Copy link

aberba commented Oct 12, 2020

I don't seem to have any router.push() or history action on the page... This is the error I get for mine...something about n is not a function

WhatsApp Image 2020-09-15 at 1 52 32 PM

@talaikis
Copy link

+1 with 9.5.5

@ralppppy
Copy link

Still having this issue I've tried 9.5.3-canary.21. I'm also using a hash in my link. I can use normal a tag to fix it but the page reloads, and it doesnt feel like a react website anymore

@akratzel
Copy link

Facing the same issue. Any updates or solution?

@conordavidson
Copy link

Still having an issue here. Any updates?

@aberba
Copy link

aberba commented Apr 28, 2021

The useEffect function of mine was has a return null which was causing my problem. Removing that fixed my issues. You may just use return without a value. useEffect expects only a cancellation function to be returned if any, else nothing else should be returned.

@cambaughn
Copy link

cambaughn commented Jul 22, 2021

I'm still experiencing this issue. Forward and back buttons work as long as I don't refresh, but after a refresh on a page with dynamic content, pressing the back button results in the url updating correctly but the page not rendering the correct page.

I'm not getting any errors, either. The page just doesn't re-render with the content for the correct route.

@ijjk
Copy link
Member

ijjk commented Jul 22, 2021

@cambaughn that sounds related to the page state with dynamic routes, I added a note for this behavior in #26320 does the note added there help with your case?

@cambaughn
Copy link

@ijjk That makes sense, but in this case it's not an issue of navigating between the same pages with dynamic routes, it's any page at all, I'm finding.

I finally solved it, and it turned out to be an issue with some code I had to fix scroll restoration on my app.

Here is the code before the fix:

  const handleScrollRestoration = () => {
    window.history.scrollRestoration = "manual";

    const cachedScroll = [];

    router.events.on("routeChangeStart", () => {
      cachedScroll.push([window.scrollX, window.scrollY]);
    });

    router.beforePopState(() => {
      if (cachedScroll.length > 0) {
        const [x, y] = cachedScroll.pop();
        setTimeout(() => {
          window.scrollTo(x, y);
        }, 100);

        return true;
      } 
    });
  }

The issue was that I didn't have router.beforePopState returning true unless it was also performing a scroll restoration. So, when I refreshed the page, it didn't have anything in the cachedScroll array. So, the fix was to add an additional else to the function.

    router.beforePopState(() => {
      if (cachedScroll.length > 0) {
        const [x, y] = cachedScroll.pop();
        setTimeout(() => {
          window.scrollTo(x, y);
        }, 100);

        return true;
      } else {
        return true;
      }
    });

@atulpe
Copy link

atulpe commented Aug 2, 2021

@ayush-pe this seems to be related

@ImTemporaryHere
Copy link

still have this problem with clicking back after page was reloaded, just nothing changes.

@brunobraga95
Copy link

Same here

@ilibilibom
Copy link

+1

@anerror404
Copy link

Have been facing this problem for long time. Problem still exists after updating from next js version 9 to the latest. it's a pretty major issue.

@akratzel
Copy link

Have been facing this problem for long time. Problem still exists after updating from next js version 9 to the latest. it's a pretty major issue.

Make sure you're using no third party library that messes with your browsers history. Taking care of a clean history fixed it for me.
The lib that caused the issue for me was snipcart.

@icyJoseph
Copy link
Contributor

icyJoseph commented Aug 30, 2021

Have been facing this problem for long time. Problem still exists after updating from next js version 9 to the latest. it's a pretty major issue.

Make sure you're using no third party library that messes with your browsers history. Taking care of a clean history fixed it for me.
The lib that caused the issue for me was snipcart.

This! I had posted what I thought was a force fix, but after walking away from it for a coffee break, I realized it did nothing, so I began to disconnected other libraries, and to my surprise it was the Service Worker I had. It was capturing .json requests and messing up with the back button. Specifically it was MSW, once I turned it off, things worked swell.

@morganhiep210
Copy link

morganhiep210 commented Oct 13, 2021

For my solution don't use the component Link of Next switch to using the tag a. hope it helps someone.

@douglasjunior
Copy link

douglasjunior commented Jan 17, 2022

Have been facing this problem for long time. Problem still exists after updating from next js version 9 to the latest. it's a pretty major issue.

Make sure you're using no third party library that messes with your browsers history. Taking care of a clean history fixed it for me. The lib that caused the issue for me was snipcart.

We are having this problem when using react-scroll, however this seens to be a limitation with NextJS, because we use react-scroll with gatsby and with react-router without any problem.

Did anyone manage to solve it?

@fudgi
Copy link

fudgi commented Jan 31, 2022

i solved my problem by finding that router.replace triggers on every page by mistake

@github-actions
Copy link
Contributor

github-actions bot commented Mar 3, 2022

This closed issue has been automatically locked because it had no new activity for a month. If you are running into a similar issue, please create a new issue with the steps to reproduce. Thank you.

@github-actions github-actions bot locked as resolved and limited conversation to collaborators Mar 3, 2022
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests