vercel / next.js

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

v12.2 up to v12.3.2-canary.22 handleHardNavigation Invariant: attempted to hard navigate to the same URL #38171

Closed willemliufdmg closed 2 years ago

willemliufdmg commented 2 years ago

Verify canary release

Provide environment information

Deployed to Vercel

Operating System:
      Platform: win32
      Arch: x64
      Version: Windows 10 Pro
    Binaries:
      Node: 16.13.1
      npm: N/A
      Yarn: N/A
      pnpm: N/A
    Relevant packages:
      next: 12.3.2-canary.22
      eslint-config-next: 12.3.1
      react: 18.2.0
      react-dom: 18.2.0

What browser are you using? (if relevant)

Not relevant

How are you deploying your application? (if relevant)

Vercel

Describe the Bug

It seems that since Next.js v12.2 the internal router does an extra fetch for the current page.js. This didn't happen in the older versions of Nextjs (see screenshots below). If the current URL is a dynamic route and is rewritten (our case in Middleware) the extra page.js fetch will result in a 404. This causes an attempt to reload the current page which then runs into the handleHardNavigation error Invariant: attempted to hard navigate to the same URL.

Current production Next.js v12.1: image

Develop Next.js v12.2: image image

Expected Behavior

Should just load the page without errors.

Link to reproduction

https://router-3zllgxvkw-fdmediagroep.vercel.app/nieuws

To Reproduce

Minimal reproduction repo: https://github.com/FDMediagroep/router-bug

Next Middleware rewrite rules:

    ...
    {
      source: /^\/nieuws$/,
      destination: '/nieuws/overview/1',
    },
    {
      source: /^\/nieuws\?page=(?<pageNr>\d+)/gi,
      destination: '/nieuws/overview/$<pageNr>',
    },
    ...

Navigating to /nieuws will result in the error as described in the bug description for Next.js since v12.2. But not on the older version v12.1.

willemliufdmg commented 2 years ago

Minimal code example to demo the bug.

GitHub: https://github.com/FDMediagroep/router-bug Created with: npm init create-app router-bug -- --ts

Demo app deployed on Vercel: https://router-3zllgxvkw-fdmediagroep.vercel.app/

Fixed since next@12.3.2-canary.25: https://router-bug.vercel.app/

Navigate to https://router-3zllgxvkw-fdmediagroep.vercel.app/nieuws to see the error in the browser debug console.

deltasierra96 commented 2 years ago

Did you have any luck fixing this issue? Currently facing the same thing when handling locales in the middleware. If I remove the middleware file, the 404 returns error free.

willemliufdmg commented 2 years ago

I've even tried with middleware config to exclude all URLs starting with _next

/**
 * Configure which routes should pass through the Middleware.
 * Exclude all `_next` urls.
 */
export const config = {
  matcher: ['/', '/:notunderscore((?!_next).+)'],
};

I see that the config has effect but the error remains.

Marcelx8 commented 2 years ago

So far this has worked for me:

if (request.nextUrl.pathname.startsWith('/_next')) {
    return NextResponse.next();
}
willemliufdmg commented 2 years ago

So far this has worked for me:

if (request.nextUrl.pathname.startsWith('/_next')) {
  return NextResponse.next();
}

I've seen your suggestion. However it's not entirely the same problem as I'm experiencing. My problem explicitly occurs when rewriting certain URL's e.g:

/nieuws -> /nieuws/overview/1

/nieuws?page=2 -> /nieuws/overview/2

Upon navigating to /nieuws Next.js will try to fetch nieuws.json which doesn't exist and results in an error like so: image

image

Once deployed to Vercel the errors are only logged to the browser console (but I don't know if anything is functionally broken). During local development this error results in a popup which is annoying as it happens with every hot-module reload/page load.

During local development the error message is a bit more clear: image

snax4a commented 2 years ago

In my case I am experiencing this error when I am on 404 page (non existing route) and on that page i try to navigate to the same non existing route using next link. I am not rewriting any URL and not using middleware

The issue persists on both 12.2.0 and 12.2.1-canary.2

next info:

    Operating System:
      Platform: darwin
      Arch: x64
      Version: Darwin Kernel Version 21.5.0: Tue Apr 26 21:08:22 PDT 2022; root:xnu-8020.121.3~4/RELEASE_X86_64
    Binaries:
      Node: 16.15.1
      npm: 8.11.0
      Yarn: 1.22.17
      pnpm: 7.1.9
    Relevant packages:
      next: 12.2.1-canary.2
      eslint-config-next: 12.2.0
      react: 18.2.0
      react-dom: 18.2.0
meotimdihia commented 2 years ago

@balazsorban44 Please help check this problem.

msedge_2022-07-09_10-37-02

floflock commented 2 years ago

I am facing the same issue, only deployed on vercel.

image
    Operating System:
      Platform: darwin
      Arch: arm64
      Version: Darwin Kernel Version 21.5.0: Tue Apr 26 21:08:37 PDT 2022; root:xnu-8020.121.3~4/RELEASE_ARM64_T6000
    Binaries:
      Node: 18.6.0
      npm: 8.13.2
      Yarn: 1.22.19
      pnpm: N/A
    Relevant packages:
      next: 12.2.2
      eslint-config-next: 12.2.2
      react: 18.2.0
      react-dom: 18.2.0

I have a middleware up and running, but I am not sure if this is the initiator.

import { NextRequest, NextResponse } from 'next/server'

const PUBLIC_FILE = /\.(.*)$/

export default function middleware(request: NextRequest) {
  const shouldHandleLocale =
    !PUBLIC_FILE.test(request.nextUrl.pathname) &&
    !request.nextUrl.pathname.includes('/api/') &&
    !request.nextUrl.pathname.includes('/_next/') &&
    request.nextUrl.locale === 'default'

  if (shouldHandleLocale) {
    const url = request.nextUrl.clone()
    url.pathname = `/de-AT${request.nextUrl.pathname}`
    return NextResponse.redirect(url)
  }

  return NextResponse.next()
}

The compiled output shows the file in place: /_next/data/5CfMudfvmgVsF9aMEgIXj/de-AT/p/BE25-roll.json

bramvdpluijm commented 2 years ago

Currently experiencing this issue as well when not using any _middleware.

vajdagabor commented 2 years ago

I am experiencing this issue with empty middleware too, on Next.js v12.2.2, when deployed on Vercel.

Pages on dynamic routes are hard loaded, non-dynamic ones are fine. After navigating to a dynamic path, then back to a non-dynamic path, SWR content is hard fetched, not using the cache.

My middleware.ts file is in the root. Removing the middleware solves the issue, and even an empty middleware makes the problem appear:

export default async function middleware() {}

There are two error messages in the browser's console:

Error: Failed to lookup route: /_next/data/WmofwclRGrKIzLl3u1raO/exercise/beginner-program.json

and:

Unhandled Promise Rejection: Error: Invariant: attempted to hard navigate to the same URL /exercise/beginner-program

Local builds work fine.

davydog187 commented 2 years ago

This issue is absolutely destroying my error reporting. Has anyone been able to find a way to suppress the warnings until we find a bugfix?

willemliufdmg commented 2 years ago

This issue is absolutely destroying my error reporting. Has anyone been able to find a way to suppress the warnings until we find a bugfix?

I haven't seen this error message with v12.2.3 anymore. So maybe you can try that version.

davydog187 commented 2 years ago

I am still seeing this issue on v12.2.3

$ npm list
├── @heroicons/react@1.0.6
├── @portabletext/react@1.0.6
├── @sanity/client@3.3.2
├── @sanity/image-url@1.0.1
├── @sanity/webhook@1.0.2
├── @sentry/nextjs@7.8.0
├── @tailwindcss/typography@0.5.2
├── autoprefixer@10.4.7
├── classnames@2.3.1
├── eslint-config-next@12.2.3
├── eslint@8.20.0
├── next-sanity@0.6.0
├── next@12.2.3
├── postcss@8.4.14
├── prettier-plugin-tailwindcss@0.1.11
├── prettier@2.7.1
├── react-dom@18.2.0
├── react@18.2.0
└── tailwindcss@3.1.4

You can see the issue in action here

Node: 16.x Platform: Vercel

I have a single middleware that looks like this

// <project root>/middleware.js

import { NextResponse } from "next/server";

export function middleware(request) {
  // Added from suggestion above
  // UPDATE: I removed this if and it also is still broken
  if (request.nextUrl.pathname.startsWith("/_next")) {
    return NextResponse.next();
  }

  if (request.nextUrl.pathname.startsWith("/tags")) {
    return NextResponse.redirect(new URL("/news", request.url));
  }

  if (request.nextUrl.pathname.startsWith("/category")) {
    return NextResponse.redirect(new URL("/news", request.url));
  }

  if (request.nextUrl.pathname.startsWith("/author/")) {
    return NextResponse.redirect(new URL("/about", request.url));
  }
}
floflock commented 2 years ago

Cannot confirm @willemliufdmg. I've updated my packages and deployed it: https://kaminholz-vercel-opffmn53w-floflock.vercel.app/de-AT/p/BE25-net

The message is still there.

    Operating System:
      Platform: darwin
      Arch: arm64
      Version: Darwin Kernel Version 21.5.0: Tue Apr 26 21:08:37 PDT 2022; root:xnu-8020.121.3~4/RELEASE_ARM64_T6000
    Binaries:
      Node: 18.6.0
      npm: 8.13.2
      Yarn: 1.22.19
      pnpm: N/A
    Relevant packages:
      next: 12.2.3
      eslint-config-next: 12.2.3
      react: 18.2.0
      react-dom: 18.2.0
willemliufdmg commented 2 years ago

Cannot confirm @willemliufdmg. I've updated my packages and deployed it: https://kaminholz-vercel-opffmn53w-floflock.vercel.app/de-AT/p/BE25-net

The message is still there.

    Operating System:
      Platform: darwin
      Arch: arm64
      Version: Darwin Kernel Version 21.5.0: Tue Apr 26 21:08:37 PDT 2022; root:xnu-8020.121.3~4/RELEASE_ARM64_T6000
    Binaries:
      Node: 18.6.0
      npm: 8.13.2
      Yarn: 1.22.19
      pnpm: N/A
    Relevant packages:
      next: 12.2.3
      eslint-config-next: 12.2.3
      react: 18.2.0
      react-dom: 18.2.0

I've updated the original post to reflect the most current environment information. In the router-bug demo I've updated next to use 12.2.4-canary.4 and can confirm that the error message still shows.

hi-paul commented 2 years ago

In my case, I also use dynamic route and just adding an empty middleware causes infinite reload with the above error.

However if i change in korean, it works with the error but it's a bit slow.

If I remove the empty middleware file, it's fast and everything works fine.

Operating System:
      Platform: darwin
      Arch: x64
      Version: Darwin Kernel Version 21.5.0: Tue Apr 26 21:08:37 PDT 2022; root:xnu-8020.121.3~4/RELEASE_ARM64_T6000
    Binaries:
      Node: 16.13.0
      npm: 8.1.0
      Yarn: 1.22.10
      pnpm: N/A
    Relevant packages:
      next: 12.2.3
      eslint-config-next: N/A
      react: 18.2.0
      react-dom: 18.2.0
hi-paul commented 2 years ago

My issue has been resolved since updating to 12.2.4

nikolajvonholck commented 2 years ago

Same: My issue has also been resolved since updating to 12.2.4.

ijjk commented 2 years ago

Hi, taking another look at the initial reproduction it looks like this isn't working correctly as the rewrite is dependent on the search value which is causing a rewrite to occur for a direct visit but not on a client transition since the _next/data request includes all search values.

The rewrites done in middleware need to match between direct visit and client transition otherwise the query hydration can fail to resolve correctly.

After fixing the rewrite logic in the reproduction it appears to be working correctly in v12.2.4 so I'm gonna close this for now as others are mentioning above it is resolved for them in this version as well.

If you're still having troubles with this after fixing the above code issue in the middleware please provide additional information and we can investigate further!

bryanrsmith commented 2 years ago

I updated from 12.1.6 to 12.2.4 yesterday and this error has started appearing in my logs. I haven't been able to reproduce it myself.

@ijjk Could you clarify the suspected source of the problem so I can try to come up with a repro? I have middleware performing redirects, but it does not depend on the querystring and I can't think of a reason it would behave differently between direct visits and client transitions. It uses cookies and request.geo to redirect users to an appropriate locale, and it seems to work fine for ~99.75% of my users. The only pattern I see is that it has never occurred on the default locale.

ijjk commented 2 years ago

It uses cookies and request.geo to redirect users

There could be a potential race condition with this redirect handling between the direct visit and a client transition if the cookie is manipulated at all e.g. if the cookie is initially empty and then set after direct visit. A link to a repo where this is occurring would make it easier to say.

Note we are looking into better handling for this error.

bryanrsmith commented 2 years ago

Interesting. The cookie is only set if the user manually makes a preference change, so that sounds less likely to me. The site is https://99spokes.com if you want to poke around. I'd gladly provide a minimal repro if I could figure out how to reproduce it :-) I've logged 260 occurrences out of ~150K total page views.

Oh! I just noticed every single one came from an apple device-- 248 from iOS and 12 from macOS.

bryanrsmith commented 2 years ago

Maybe Safari's IP address masking feature is causing these users geoip data to jump between regions during the same session. I can try setting a cookie when the middleware makes a decision based on geo, and opt for the potential race condition you mention instead.

bryanrsmith commented 2 years ago

No luck. The Safari "Hide IP address" setting is right next to a "Block all cookies" setting, so maybe these users are also blocking cookies? I'm not sure what I can do to 100% guarantee that two independent requests always return the same result. Do you have any suggestions @ijjk? Is it possible for Next to handle this internally, or silence the error in production builds?

ijjk commented 2 years ago

Hmm ideally the requests don't return differing content/responses as long as the requests are made from the same session. Possibly this isn't what is occurring here. Do you have a stack trace from where you've seen this occur?

bryanrsmith commented 2 years ago

Unfortunately I only have a minified stack trace from error reporting.

File https://99spokes.com/_next/static/chunks/main-458b2dad1fdae608.js  line 1 col 74370 in J
File https://99spokes.com/_next/static/chunks/main-458b2dad1fdae608.js  line 1 col 85835 in [anonymous]
File https://99spokes.com/_next/static/chunks/main-458b2dad1fdae608.js  line 1 col 15113 in l
File https://99spokes.com/_next/static/chunks/main-458b2dad1fdae608.js  line 1 col 14898 in [anonymous]
File https://99spokes.com/_next/static/chunks/main-458b2dad1fdae608.js  line 1 col 882 in r
File https://99spokes.com/_next/static/chunks/main-458b2dad1fdae608.js  line 1 col 1088 in u
File https://99spokes.com/_next/static/chunks/main-458b2dad1fdae608.js  line 1 col 1147 in [anonymous]
File [native code] line (unknown) in Promise
File https://99spokes.com/_next/static/chunks/main-458b2dad1fdae608.js  line 1 col 1038 in [anonymous]
File https://99spokes.com/_next/static/chunks/main-458b2dad1fdae608.js  line 1 col 90083 in [anonymous]
File https://99spokes.com/_next/static/chunks/main-458b2dad1fdae608.js  line 1 col 15113 in l
File https://99spokes.com/_next/static/chunks/main-458b2dad1fdae608.js  line 1 col 14898 in [anonymous]
File https://99spokes.com/_next/static/chunks/main-458b2dad1fdae608.js  line 1 col 882 in r
File https://99spokes.com/_next/static/chunks/main-458b2dad1fdae608.js  line 1 col 1124 in c
File [native code] line (unknown) in promiseReactionJob
grayaustinc commented 2 years ago

So this issue seems to be very similar to the same issue that I'm currently having. After putting together a demo, I believe I may have found out what the problem could be. Vercel: https://next-12-2-4-rewrite-bug.vercel.app/ Github: https://github.com/grayaustinc/next-12.2.4-rewrite-bug From what I could test, it seems to be a problem with trailing slashes at the end of the rewrite source. if @willemliufdmg could somehow update their middleware rewrite rules to not include the trailing slash in the source to confirm, that would be a good way to find out that it's not just my specific example. After debugging things on willemliufdmg demo, I found that changing the fallback in getStaticPaths from "blocking" to true/false seems to solve the issue for his specific situation. There are still issues with the way rewrites are being handled that is causing the errors in some way I believe.

The Invariant error also appears on the home page in my example since I am rewriting from / to /home/ and since I can't really remove the slash from the source, I can only assume that ending the source in a slash is the problem.

robcaldecott commented 2 years ago

We are seeing this error appear whenever we update our NextJS application (we are self-hosting). It seems to be attempting to load old data which fails and forces Next to reload the page. It seems harmless but clutters our Sentry logs with noise and we can't seem to ignore the Sentry issue.

We're using SSR (getServerSideProps) yet the logs show an error with static props:

GET /_next/data/61e198fa74d5fbd46c04cf97ade59d0ddd5e9ee9/fleets/3e79541e-9f39-4b13-81f2-d1652a83a8d2.json?fleetuuid=3e79541e-9f39-4b13-81f2-d1652a83a8d2 [404]

Error: Failed to load static props

Error: Invariant: attempted to hard navigate to the same URL /fleets/3e79541e-9f39-4b13-81f2-d1652a83a8d2 https://fleet.zego.com/fleets/3e79541e-9f39-4b13-81f2-d1652a83a8d2

It looks like a GET for the _next/data fails (old URL from before the app was updated maybe?) which causes a Failed to load static props error which in turn forces a hard reload which generates the hard navigate error.

We only noticed this since 12.2.x. We use a custom generateBuildId in our next.config.js but other than that everything is standard and we have no middleware at all.

Being able to ignore these errors would be great.

Shramkoweb commented 2 years ago

Have the same problem on "next": "12.2.4", Safari - Version:15.6

Error: Invariant: attempted to hard navigate to the same URL /blog https://shramko.dev/blog at handleHardNavigation(./node_modules/next/dist/shared/lib/router/router.js:336:6) at ? (./node_modules/next/dist/shared/lib/router/router.js:857:28) at generatorResume([native code]) at c(./node_modules/@swc/helpers/lib/_async_to_generator.js:24:1) at h(./node_modules/@swc/helpers/lib/_async_to_generator.js:13:1) at ? (./node_modules/@swc/helpers/lib/_async_to_generator.js:18:10) at Promise([native code]) at ? (./node_modules/@swc/helpers/lib/_async_to_generator.js:10:1) at generatorResume([native code]) at c(./node_modules/@swc/helpers/lib/_async_to_generator.js:24:1) at _throw(./node_modules/@swc/helpers/lib/_async_to_generator.js:16:1) at promiseReactionJob([native code])

ijjk commented 2 years ago

If you are able to provide a reproduction where this is occurring in the latest version v12.2.5 and it's not specific to the above mentioned case where different responses are being returned from middleware between initial visit and hydration it would be good to open a fresh issue so we can investigate this further!

We can also investigate suppressing this error in non-fatal cases.

efrenaguilar95 commented 2 years ago

In my case I am experiencing this error when I am on 404 page (non existing route) and on that page i try to navigate to the same non existing route using next link. I am not rewriting any URL and not using middleware

The issue persists on both 12.2.0 and 12.2.1-canary.2

next info:

    Operating System:
      Platform: darwin
      Arch: x64
      Version: Darwin Kernel Version 21.5.0: Tue Apr 26 21:08:22 PDT 2022; root:xnu-8020.121.3~4/RELEASE_X86_64
    Binaries:
      Node: 16.15.1
      npm: 8.11.0
      Yarn: 1.22.17
      pnpm: 7.1.9
    Relevant packages:
      next: 12.2.1-canary.2
      eslint-config-next: 12.2.0
      react: 18.2.0
      react-dom: 18.2.0

Hello all. I am on v12.2.5 and am also getting this. Have a Link component that links to a non-existent page. First time I use it I get a 404, as expected. However, if I click it while in the same 404 page I get the unhandled runtime error. Purely on a local host no middleware or external dependencies whatsoever.

grayaustinc commented 2 years ago

Decided to look at this issue again to try and provide some information. I noticed in the Network tab on chrome that the request for the Json file is labeled as nieuws.json?overview=1 which is incorrect and instead should be labeled as nieuws.json?page=1. This means that your middleware rewrite is not even matching the source /^\/nieuws\?page=(?<pageNr>\d+)/gi. Because of this, the response is missing the headers

x-nextjs-matched-path: /nieuws/overview/[...overview]
x-nextjs-rewrite: /nieuws/overview/1

which causes the nextjs response tree to continue the request to nieuws.js which does not exists, throwing errors. Upon looking further, the overview=1 appears to be coming from the router object which pulls data from the __NEXTDATA_\ html script object. This means that the initial document response is wrong making this a server side issue. Like my comment from above, setting the fallback to true instead of blocking changes the response in a way that does not throw the errors.

__NEXTDATA_\ JSON Responses

fallback: "blocking";

{
    "props": {
        "pageProps": {
            "page": 1
        },
        "__N_SSG": true
    },
    "page": "/nieuws/overview/[...overview]",
    "query": {
        "overview": ["1"]
    },
    "buildId": "development",
    "isFallback": false,
    "gsp": true,
    "scriptLoader": []
}

fallback: true;

{
    "props": {
        "pageProps": {},
        "__N_SSG": true
    },
    "page": "/nieuws/overview/[...overview]",
    "query": {},
    "buildId": "development",
    "isFallback": true,
    "gsp": true,
    "scriptLoader": []
}

Hopefully someone who has a better understanding of how the server works can figure out why the response is different for a blocking fallback.

thijsadrmat commented 2 years ago

I was experiencing this error as well, so for those struggling with this a well. In my case I had a fallback rewrite (for incremental adaption) for all paths in the next.config.js, I would expect this rewrite not to be triggered after rewriting to a next route from the middleware. After removing this fallback in the config, my rewrites from the middleware work as expected. I was able to debug the function that created this error, and it said it would rewrite externally (externalDest: true). To fix it I'll be moving all rewrites from config to the middleware. Hopefully that solves the issue for good.

jonspark commented 2 years ago

We're having this same error, starting when we updated to v12.2.5 and persisting in v12.3.0. We have all our rewrites all in middleware and there aren't any fallbacks in config. We haven't been able to replicate the problem ourselves (locally or on Vercel), but our error logging is being flooded.

The problem only goes away if we revert to v12.1.6.

willemliufdmg commented 2 years ago

I've updated the demo to use the latest canary 12.3.1-canary.1. And the error message still persists.

roxworks commented 2 years ago

For anyone coming back to this who happens to be combining multiple different nextjs projects...

Make sure your projects all have a basePath parameter set in their individual next.config.js files

The rule is you can do multiple repos and rewrites, but they can't have the same paths, including /

so, TL;DR if you have two projects, #1 is "home" and #2 is "blog"

Make sure the blog next.config.js has this:

basePath: "/blog"

and then in your rewrites, change to

{ source: '/blog/:path*', destination: "https://YOUR_BLOG_URL/blog/:path*", }

Not sure that this is exactly the issue others are having, but got here from Googling the same error message and this was my issue

meotimdihia commented 2 years ago

In my case, I don't host my website in Vercel. it happens when the error Error: Failed to load static props appeared. image

ghost commented 2 years ago

in my case i am deploying in azure with docker and i have the same error

tiago-sanches-bairesdev commented 2 years ago

My team and I are experiencing this error yet. We are using the v12.3.0. We hardly can reproduce it for sure, I just could a couple of times and it was reloading the page non-stop. As some comments above, our Sentry log is has a bunch of this error report.

Following the documentation I could notice that we have some redirects on our next.config.file, and we wrote this redirect call precisely as in the docs but tbh we didn't believe this is the cause of this error, because we try to match the redirects URL in next.confi.js function call and the Sentry errors URL and no one of them matches at all.

So we believe that it could be something in middleware. Our middleware is in the root as the next upgrade guide to v.12.2 asked for this change. We do a couple of URL comparisons on middleware to redirect to another URL, I'm currently suspecting about it.

Besides that, I noticed in Sentry that the mostly errors is like /_next/data/generated_string/[slug].json?slug=slug&another_bunch_of_params=xxxxx [404], and followed by an Error: Failed to load script and at the end, we got the exception Error: Invariant: attempted to hard navigate to the same URL.

It's really frustrating to not be able to reproduce it to have sure of how we can handle and try to solve this error. So any help and suggestion that could help us are welcomed.

willemliufdmg commented 2 years ago

My team and I are experiencing this error yet. We are using the v12.3.0. We hardly can reproduce it for sure, I just could a couple of times and it was reloading the page non-stop. As some comments above, our Sentry log is has a bunch of this error report.

Following the documentation I could notice that we have some redirects on our next.config.file, and we wrote this redirect call precisely as in the docs but tbh we didn't believe this is the cause of this error, because we try to match the redirects URL in next.confi.js function call and the Sentry errors URL and no one of them matches at all.

So we believe that it could be something in middleware. Our middleware is in the root as the next upgrade guide to v.12.2 asked for this change. We do a couple of URL comparisons on middleware to redirect to another URL, I'm currently suspecting about it.

Besides that, I noticed in Sentry that the mostly errors is like /_next/data/generated_string/[slug].json?slug=slug&another_bunch_of_params=xxxxx [404], and followed by an Error: Failed to load script and at the end, we got the exception Error: Invariant: attempted to hard navigate to the same URL.

It's really frustrating to not be able to reproduce it to have sure of how we can handle and try to solve this error. So any help and suggestion that could help us are welcomed.

You can reproduce the problem with the Demo I linked to in the original post. The Demo has been updated to use next@12.3.2-canary.22.

willemliufdmg commented 2 years ago

This issue has been closed but the problem has not been resolved.

ijjk commented 2 years ago

@willemliufdmg as mentioned in https://github.com/vercel/next.js/issues/38171#issuecomment-1207443525 the bug is in the middleware handling itself and not Next.js as it's handling the /_next/data request (client-data) different than the direct visit.

These requests must match or it causes a divergence on the client. Potentially we could add an error for this although it's tricky to detect.

bryanrsmith commented 2 years ago

@ijjk It would be great if Vercel could provide more official documentation, recommendations, or mitigation for this issue. I've put a lot of time into trying to resolve this error with no success. I don't believe my middleware is doing anything that's not demonstrated in official examples, but the error persists. I feel blocked from updating nextjs because of this.

AryanJ-NYC commented 2 years ago

I see this error pop up in my Sentry and I have zero middlewares.

willemliufdmg commented 2 years ago

@willemliufdmg as mentioned in https://github.com/vercel/next.js/issues/38171#issuecomment-1207443525 the bug is in the middleware handling itself and not Next.js as it's handling the /_next/data request (client-data) different than the direct visit.

These requests must match or it causes a divergence on the client. Potentially we could add an error for this although it's tricky to detect.

This error also shows during local development. I can only assume that it has nothing to do with Vercel at that time but I could be wrong.

imhuynq commented 2 years ago

In my project (no middleware and rewrites), this error happened when user navigate to same current URL (e.g: in homepage, user click logo header) after a new deployment

ijjk commented 2 years ago

Hi, we have recently updated how this specific case is handled and the initial reproduction should no longer be causing issues in v12.3.2-canary.25 of Next.js, please update and give it a try!

willemliufdmg commented 2 years ago

Hi, we have recently updated how this specific case is handled and the initial reproduction should no longer be causing issues in v12.3.2-canary.25 of Next.js, please update and give it a try!

I can confirm that this case has now been fixed in next@12.3.2-canary.25.

Thank you all@next.js for solving this bug!

halukaydogan commented 2 years ago

just DOUBLE check the href at Link <Link href="????????" as="/apps"> you click and at next.config.js rewrites destination are same... if they are not same it makes that error...

shadowgroundz commented 2 years ago

Same issue on Next 13.0

Operating System:
  Platform: darwin
  Arch: arm64
  Version: Darwin Kernel Version 22.1.0: Sun Oct  9 20:14:30 PDT 2022; root:xnu-8792.41.9~2/RELEASE_ARM64_T8103
Binaries:
  Node: 16.18.1
  npm: 8.19.2
  Yarn: 1.22.19
  pnpm: 7.14.2
Relevant packages:
  next: 13.0.2
  eslint-config-next: 13.0.2
  react: 18.2.0
  react-dom: 18.2.0