Skip to content

This issue was moved to a discussion.

You can continue the conversation there. Go to discussion →

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

Error: Invariant: attempted to hard navigate to the same URL on iPhone #43088

Closed
1 task done
bartek2341 opened this issue Nov 18, 2022 · 57 comments
Closed
1 task done
Labels
bug Issue was opened via the bug report template. linear: next Confirmed issue that is tracked by the Next.js team. please add a complete reproduction The issue lacks information for further investigation

Comments

@bartek2341
Copy link

bartek2341 commented Nov 18, 2022

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
Binaries:
Node: 18.12.0
npm: N/A
Yarn: N/A
pnpm: N/A
Relevant packages:
next: 13.0.3
eslint-config-next: 13.0.3
react: 18.2.0
react-dom: 18.2.0

What browser are you using? (if relevant)

Google Chrome v107.0.5304.107

How are you deploying your application? (if relevant)

next start, Digital Ocean

Describe the Bug

Hi, I just connected my production next.js app to the error tracker and noticed a lot of errors, which all give:
Error: Invariant: attempted to hard navigate to the same URL https://[domain-name]/[locale].

The error occurs only on localized versions of website and only on iPhone mainly safari v14, 15, 16 but also on Edge Mobile Version:107.0.1418 and Chrome Mobile iOS Version:107.0.5304.

error

Source of all errors:
{snip} dLocale.addLocale(router.asPath,router.locale)))throw Error("Invariant: attempted to hard navigate to the same URL ".concat(url," ").concat( {snip}

Example log:
log

It seems that after navigation to the same localized url it can't find the [locale].json file. This website does not implement getServerSideProps or getStaticProps.
I've tested all link components both on production, development, emulated safari browser but I haven't noticed any errors/warnings in the console and I don't know what can cause this behavior for iPhone visitors.

I was using Next.js v12.2.4 but the error still occurs after upgrading to v13. I am also using next-translate v1.6.0 in my project and I don't know if the error can be related to this package or to next.js itself.

Thanks

next.config.js
const nextTranslate = require("next-translate");
const { withSentryConfig } = require("@sentry/nextjs");

const moduleExports = {
  ...nextTranslate(),

  sentry: {
    hideSourceMaps: true,
  },
};

const sentryWebpackPluginOptions = {
  silent: true,
};

module.exports = withSentryConfig(moduleExports, sentryWebpackPluginOptions);
i18n.json
{
  "locales": ["pl", "en", "es", "ru", "tr", "zh", "hi", "fr", "ar", "bn", "pt", "id", "de", "it"],
  "defaultLocale": "pl",
  "localeDetection": false,
  "pages": {
    "*": ["common"],
    "/": ["index"],
  }
}

Expected Behavior

Normal navigation to the same localized route on iPhone device.

Link to reproduction - Issues with a link to complete (but minimal) reproduction code will be addressed faster

Not relevant

To Reproduce

Not relevant

NEXT-1367

@bartek2341 bartek2341 added the bug Issue was opened via the bug report template. label Nov 18, 2022
@wadehammes

This comment was marked as off-topic.

@balazsorban44 balazsorban44 added the please add a complete reproduction The issue lacks information for further investigation label Nov 18, 2022
@ijjk
Copy link
Member

ijjk commented Nov 22, 2022

Hi, there were changes related to this in the most recent version of Next.js v13.0.4, can you please update and give it a try!

@bartek2341
Copy link
Author

Hello, unfortunately updating to version 13.0.4 did not help. It's hard to reproduce the error as it only shows on iPhone but I think it might be similar to the example from #38171.

ios

@ijjk
Copy link
Member

ijjk commented Nov 23, 2022

The above example is fixed in the latest version, can you confirm those errors are in fact from the release after updating to v13.0.4?

@bartek2341
Copy link
Author

Yes, sentry is still screaming about this error even in v13.0.5-canary.6.

@DavidWells
Copy link

I'm seeing this as well. Has anyone found a fix?

Details:

browser = Chrome 105.0.0 
browser.name = Chrome 
environment = production 
handled = no 
mechanism = onunhandledrejection 
os = Windows 10

@balazsorban44
Copy link
Member

We cannot recreate the issue with the provided information. Please add a reproduction in order for us to be able to investigate.

Why was this issue marked with the please add a complete reproduction label?

To be able to investigate, we need access to a reproduction to identify what triggered the issue. We prefer a link to a public GitHub repository (template), but you can also use a tool like CodeSandbox or StackBlitz.

To make sure the issue is resolved as quickly as possible, please make sure that the reproduction is as minimal as possible. This means that you should remove unnecessary code, files, and dependencies that do not contribute to the issue.

Please test your reproduction against the latest version of Next.js (next@canary) to make sure your issue has not already been fixed.

I added a link, why was it still marked?

Ensure the link is pointing to a codebase that is accessible (e.g. not a private repository). "example.com", "n/a", "will add later", etc. are not acceptable links -- we need to see a public codebase. See the above section for accepted links.

What happens if I don't provide a sufficient minimal reproduction?

Issues with the please add a complete reproduction label that receives no meaningful activity (e.g. new comments with a reproduction link) are automatically closed and locked after 30 days.

If your issue has not been resolved in that time and it has been closed/locked, please open a new issue with the required reproduction.

I did not open this issue, but it is relevant to me, what can I do to help?

Anyone experiencing the same issue is welcome to provide a minimal reproduction following the above steps. Furthermore, you can upvote the issue using the 👍 reaction on the topmost comment (please do not comment "I have the same issue" without repro steps). Then, we can sort issues by votes to prioritize.

I think my reproduction is good enough, why aren't you looking into it quicker?

We look into every Next.js issue and constantly monitor open issues for new comments.

However, sometimes we might miss one or two due to the popularity/high traffic of the repository. We apologize, and kindly ask you to refrain from tagging core maintainers, as that will usually not result in increased priority.

Upvoting issues to show your interest will help us prioritize and address them as quickly as possible. That said, every issue is important to us, and if an issue gets closed by accident, we encourage you to open a new one linking to the old issue and we will look into it.

Useful Resources

@johnkoehn
Copy link

This has been an issue for six months now #38171. The other ticket has a reproducible environment. Let's please prioritize getting this fixed

@cbouwense
Copy link

bumping this issue, getting the same issues in Sentry

@bobaaaaa
Copy link
Contributor

bobaaaaa commented Dec 19, 2022

My guess is, that there is a bug in next.js since 12.2.0. This has something to do with the "back-forward-cache" in safari. See https://web.dev/bfcache/ for more infos. We could work around this bug with the following hack:

const disableBrowserBackForwardCache = `
window.addEventListener('pageshow', (event) => {
  if (event.persisted) {
    location.reload();
  }
});
`;
<script dangerouslySetInnerHTML={{ __html: disableBrowserBackForwardCache }} />

We added this <script /> element as one of the first (!) children of <Head /> (next/head). It is important, that this script is executed as fast as possible on the client.

@bobaaaaa
Copy link
Contributor

bobaaaaa commented Dec 19, 2022

I checked some canary releases of next.js. The bug was introduced in 12.1.7-canary.32. And my bet is this PR: #37431

changelog: v12.1.7-canary.31...v12.1.7-canary.32

@mohsinht
Copy link

Same, continuously getting this issue on Sentry.

Error:

Invariant: attempted to hard navigate to the same URL

Device:
Browser: Mobile Safari (Version:16.2)
Device: iPhone
OS: iOS 16.2

@bartek2341
Copy link
Author

Unfortunately, it didn't work for me either

@DavidWells
Copy link

Getting a ton of these in prod. It's hard to reproduce though. Not sure what the underlying issue is.

image

I'm unclear on what the visitor experiences when they hit this. Does the next site show the hard failure? If so, 😅, need to get a fix in asap.

Thanks for looking into this issue ❤️

@jordienr
Copy link

jordienr commented Jan 19, 2023

Getting the same issue, haven't been able to replicate it but getting sentry errors every day about it. I'm on next@13.0.6

Edit:
The error seems to happen without any user input, the page loads and 4 seconds later the error pops up. I'm starting to think it may have something to do with the cookie modal, we're using cookiebot.

@beckerei
Copy link

beckerei commented Jan 19, 2023

We also have this error in sentry, and I can reproduce it on our staging and production environment. I think it's hard/impossible to replicate this within a sandbox.

The problem manifests when we deploy a new version of our next app.
If a user is on the page and we deploy a new version you will see exactly this error in sentry and also in the browser console. The app itself continues to work, there are no issues for the user.

We also reload/refresh the page props whenever the user focuses the page again (e.g. by coming back to the browser) by using router.replace(router.asPath, undefined, { scroll: false }). So the user does not work with stale data. This might lead to the issue.

We assume it happens because of assets path changed/are not available anymore, due to the pod change, it's handled here

if (isAssetError(err) || loadErrorFail) {

No hard navigation is happening because we actually haven't changed the URL, this is when the error is logged in the console/sentry

if (url === addBasePath(addLocale(router.asPath, router.locale))) {

We are currently using next@13.1.1 but had this problem also with v12.

@bberz-groma
Copy link

I can verify that it must be related to the middleware file / method. When I remove the middleware file and method all together, I do not get this error. However, if I have a middleware file with an exported middleware method, the error returns.

@ijjk
Copy link
Member

ijjk commented Jan 20, 2023

@bberz-groma can you share the contents of your middleware file that introduces the issue and what version of Next.js you are on?

@bberz-groma
Copy link

bberz-groma commented Jan 23, 2023

@ijjk I am on 13.1.2.

I stripped down my middleware file to only include an export of a method name like so to test the theory that it is in-fact related to the middleware file / method usage.

import { NextResponse } from 'next/server';

export function middleware() {
  return NextResponse.next();
};

This results in the error seen below when I visit my deployed application
image

@stuartkeith
Copy link
Contributor

stuartkeith commented Jan 25, 2023

We have hit the same issue (our error tracker being full of "attempted to hard navigate to the same URL" errors). It can happen during normal use:

  • a user has a page loaded in the browser
  • a new version of the site is deployed, the previous build files are deleted
  • the user clicks an anchor that happens to point to the same URL the user is already on (e.g. they click the current page's entry in the navigation sidebar)
  • Next attempts to load the props for the previous build's page, which fails
  • Next attempts to refresh the current page
  • The exception is thrown because the old/new URLs are the same

In this scenario the exception seems like a false positive.

@joggienl
Copy link

joggienl commented Jan 25, 2023

Looks a bit like #44919 and #44293. I am also getting this error in dev, but on a build it also does not work as expected, specifically for the error/404 page.

@ethndotsh
Copy link

I am also having this error while using router.push().

@getayush96
Copy link

Is there any update on this ? Facing this in chrome (macos) while accessing 404 page.

@getayush96
Copy link

I used a workaround this. Instead of adding a 404 page, I added a page named [...myErrorPage] and treated this as my 404 page. All the routes which aren't matched are routed to this file, which I can handle well.

@wottpal
Copy link

wottpal commented Feb 8, 2023

Same issue here. I used redirects in my next.config.js as a workaround:

  async redirects() {
    return [
      {
        source: '/users',
        destination: '/',
        permanent: false,
      },
  // ...

@coded58
Copy link

coded58 commented Feb 9, 2023

Please can you show how you achieved this?

@nzkdevsaider
Copy link

nzkdevsaider commented Feb 12, 2023

Please can you show how you achieved this?

I don't find how to fix it. But in the meanwhile this get a fix, you can delete your custom 404 (404.js). This error happens to me when i handle inexistent pages.

@DavidWells
Copy link

We pinned to next@13.0.6 but still seeing these errors pop up...

This was error context/device on Android.

browser = Chrome Mobile 110.0.0 
browser.name = Chrome Mobile 
device = SM-G998U 
device.family = Samsung SM-G998U 
os = Android 13 os.name = Android

@Benanna2019
Copy link

Was it related to the 404 page? And rolling it back worked but after a conversation today I'm not sure why.

It seems that the issue is internal to next.

As I recall, the middleware was being fired more than once which resulted in the hard navigation errors

May be worth checking middleware as well. All we had to do was roll back.

Sorry I'm not of more help

@DavidWells
Copy link

Not a 404 page. It's to an existing page https://www.vendia.com/reconciliationless

I'm quite confused on this error TBH.

@khteh
Copy link

khteh commented Mar 27, 2023

"next": "13.2.4",
Chrome: 111.0.5563.110

@AbhiPrasad
Copy link

If you want to filter out this error from Sentry you can use beforeSend.

Sentry.init({
  beforeSend: (event) => {
    if (event.exception?.values?.[0].value.includes('Invariant: attempted to hard navigate to the same URL')) {
      return null;
    }
    return event;
  },
});

@xxwwp
Copy link

xxwwp commented Apr 18, 2023

I found that I easily implemented this bug, just by setting statusCode to a certain value. My environment is:

{
  "name": "name",
  "version": "0.1.0",
  "private": true,
  "scripts": {
    "dev": "next dev -p 3002",
    "build": "next build",
    "start": "next start -p 3000",
    "lint": "next lint"
  },
  "dependencies": {
    "@emotion/react": "^11.10.6",
    "@emotion/styled": "^11.10.6",
    "@types/node": "18.15.11",
    "@types/react": "18.0.35",
    "@types/react-dom": "18.0.11",
    "eslint": "8.38.0",
    "eslint-config-next": "13.3.0",
    "next": "13.3.0",
    "react": "18.2.0",
    "react-dom": "18.2.0",
    "typescript": "5.0.4"
  }
}

Windows 10.

The code is very simple:

import { GetServerSideProps } from "next";
import Link from "next/link";

export const getServerSideProps: GetServerSideProps = async (context) => {
  context.res.statusCode = 401;

  return {
    props: {},
  };
};

export default function ImportSysIndex() {
  return <Link href={`/import-sys`}>import system</Link>;
}

This issue occurs when using a status code between 400 and 599. Setting the status code to a value between 200 and 299 should make it work normally.

@aangindra
Copy link

Same facing this issue. Both development and production

@samknp
Copy link

samknp commented Apr 27, 2023

Same issue on "next": "13.0.4".
It occured after I changed my website to cloudflare proxy.

@ko-devHong
Copy link

Why hasn't this problem been solved yet?

@asim47
Copy link

asim47 commented May 18, 2023

Able to reproduce this issue every time when using onClick={()=> window.open("/anyURL", "_blank")}

replacing it with an achor tag fixed the issue for me.

@wottpal
Copy link

wottpal commented May 19, 2023

Also still having it. It's a pity :/

@dankolesnikov
Copy link

Facing the same issue! PLEASE FIX. Its been open since 2022..

@kryptovergleichde
Copy link

kryptovergleichde commented Jun 3, 2023

We are getting this error with the Googlebot and Android Browser, on regular pages (not 404). Currently on Nextjs 13.2. Does anyone know a recent fix for this? Thanks in advance!

@nickngqs
Copy link

I'm getting this error in development as well. It happens when im using Link to route to the current url

@timneutkens timneutkens added the linear: next Confirmed issue that is tracked by the Next.js team. label Jul 3, 2023
@leo-petrucci
Copy link

leo-petrucci commented Jul 12, 2023

This might not help but in my case I have a "root" app which uses redirects to display other Next.js apps on its domain.

// redirects config for app running at http://localhost:3000
    {
      source: "/sub-app/:match*",
      destination: `http://localhost:3002/:match*`,
    },

I'm seeing this when setting fallback: true for pages that don't have a path returned from getStaticPaths specifically on apps that are rendered by the "root" app. The error does not happen if I visit the actual URL the sub-app is running on.

Funnily enough this causes fallback to not work at all, because router.query is always {} which is quite annoying.

I've however noticed that router.asPath is correct, so I've managed to work around my pages breaking by manually splitting my queries out of that string.

My project is quite big but I'll try making a reproduction.

Very crude reproduction:

  1. My sub-app is running here
    a. It takes the query passed to it and renders it example
  2. My other app is running here
    a. It renders routes from sub-app under /sub-app

If I visit https://vwdh7f-3000.csb.app/sub-app/working (which is a page that's been defined in getStaticPaths), it works just fine. However if I visit https://vwdh7f-3000.csb.app/sub-app/not-working (which isn't defined in getStaticPaths) router.query remains {} and the Error: Invariant: attempted to hard navigate to the same URL error appears.

@maccman
Copy link

maccman commented Aug 13, 2023

Running into this error too.

@pythonwood
Copy link

same error for chat example, just change frontend port than it happend !
https://github.com/reflex-dev/reflex-chat

FRONTEND_PORT=3010 reflex run --loglevel debug

reflex --version 0.2.4

@huroh
Copy link

huroh commented Aug 21, 2023

Just started getting this error too

@muftisamiullah
Copy link

same here, Im seeing this error not sure what went wrong?

@moaazbhnas228
Copy link

I used a workaround this. Instead of adding a 404 page, I added a page named [...myErrorPage] and treated this as my 404 page. All the routes which aren't matched are routed to this file, which I can handle well.

@getayush96 Can you please explain how your workaround fixed the issue?

@olivermulari
Copy link

olivermulari commented Sep 12, 2023

We are also getting this issue. Not very often but constantly. Thinking of ignoring this in sentry since we are able to handle it in client side. Next.js version 13.2.4.

For us it is happening 95% in iOS and 5% Mac OS X. 50% of mobile safari and 45% of mobile chrome.

@paplco
Copy link

paplco commented Sep 15, 2023

having this issue also, Brave latest v1.58.124, next latest v13.4.19

@mattvb91
Copy link

Started gettinng this issue after adding this into my next.config because i need the host as part of my getServerSideProps

async rewrites() {
    return [
      {
        has: [
          {
            type: 'host',
            value: '(?<host>.*)',
          },
        ],
        source: '/',
        destination: '/:host',
      },
      {
        has: [
          {
            type: 'host',
            value: '(?<host>.*)',
          },
        ],
        source: '/:path*',
        destination: '/:host/:path*',
      },
    ];
  },

@jacobgoldfarb
Copy link

This happens when I try to add a 404.js page. Deleting middleware.js solves it, but isn't a valid fix for production. My middleware is dead simple and I don't suspect there's any logic in there that would cause this.

@samcx
Copy link
Member

samcx commented Jan 4, 2024

Hi everyone,

The latest on this issue seems to be related to a 404 page (based on the most recent comments), which seems to have deviated from the originally reported issue. A couple fixes has been pushed up since, but it seems not all edge cases have regarding this general issue been covered.

@mattvb91 @jacobgoldfarb Is it possible to create a new bug report so we can look at both of your issues separately?

I encourage others as well to create separate bug reports if they are still experiencing this on the latest version. At the moment, it is not feasible to maintain multiple edge cases (old or newly introduced) in a single large issue thread (creates a lot of noise), so I will be moving this conversation to :nextjs: Discussions soon!

@diptachoudhury
Copy link

diptachoudhury commented Feb 6, 2024

I faced the same error, for the pages which had getServerSideProps.
On adding shallow: true to router.push or next/link resolved the issue for me

@vercel vercel locked and limited conversation to collaborators Feb 6, 2024
@samcx samcx converted this issue into discussion #61734 Feb 6, 2024

This issue was moved to a discussion.

You can continue the conversation there. Go to discussion →

Labels
bug Issue was opened via the bug report template. linear: next Confirmed issue that is tracked by the Next.js team. please add a complete reproduction The issue lacks information for further investigation
Projects
None yet
Development

No branches or pull requests