next.js icon indicating copy to clipboard operation
next.js copied to clipboard

Chunk Load Error using dynamic routes ([lang])

Open leof240 opened this issue 1 year ago • 9 comments

Link to the code that reproduces this issue

https://github.com/leof240/chunk_load_error_nextauth-nextintl

To Reproduce

  1. build the project
  2. deploy on prod server
  3. go to a dynamic locale page like http:site/en
  4. the page is showing an error on chunk load error

Current vs. Expected behavior

Current: In development the site is working as expected. in a production build and production environment, the site is throwing a Chunk Load Error on the page js file behind Screenshot 2024-02-24 at 12 47 07 the buttons on the page do not work

Expected: The expected behaviour is to show a page with 2 buttons for signin and sign out. when clicking the signin button, the session is updated and after a page refresh is shown from the layout and the page. it's also showing the page title translated into different languages for the /en, /fr, / it

Provide environment information

Node 20.1

npm v9.8.1

Which area(s) are affected? (Select all that apply)

Not sure, App Router, Internationalization (i18n), Middleware / Edge (API routes, runtime)

Which stage(s) are affected? (Select all that apply)

Vercel (Deployed), Other (Deployed)

Additional context

the "next" package is updated to canary version ( 24 / 02 / 2024)

cannot reproduce the error on development environment with npm run start

leof240 avatar Feb 24 '24 12:02 leof240

I managed to remove the next-intl library and the error still persists.

it seems it's occurring when a server component has client components within a dynamic route, so not really dependednt on any external libraries.

leof240 avatar Feb 24 '24 14:02 leof240

I had a similar problem. You should add env NEXTAUTH_URL=your_domain And maybe use .env.local

Mifaresss avatar Feb 24 '24 14:02 Mifaresss

I had a similar problem. You should add env NEXTAUTH_URL=your_domain And maybe use .env.local

I'm doing that locally for another project, but it doesn't make any difference

leof240 avatar Feb 24 '24 14:02 leof240

I was able to fix the error. It's related to the previous errors on dynamic routs. There was a problem in the encoding url in server.js

The url was all lower case having the encoded square brackets lowercase therefore not properly encoded. (%5b instead of %5B)

I added a replace statement before the url processing. I'll post the code later for awareness

leof240 avatar Feb 25 '24 08:02 leof240

@leof240 Hey Leof 👋

Any chance you got that code handy? I'm currently experiencing an almost identical issue except my uri is getting encoded twice around my slug. So, I'm getting %255B instead of %5B... incredibly frustrating.

Using Next v13.5.6.

Appreciate any help!

akhrarovsaid avatar Jul 18 '24 01:07 akhrarovsaid

I added a replace statement before the url processing. I'll post the code later for awareness

May we ask for updates on this? We have a similar setup with i18n.

Luzefiru avatar Oct 25 '24 05:10 Luzefiru

I added a replace statement before the url processing. I'll post the code later for awareness

May we ask for updates on this? We have a similar setup with i18n.

Hello,

I updated the code in the branch "Fixed".

below you can find the added snippet:

let reqUrl = req.url .replaceAll(/[/g, '%5B') .replaceAll(/]/g, '%5D') .replaceAll('%5b', '%5B') .replaceAll('%5d', '%5D') ;

        //console.log('reqUrl', reqUrl)
        //console.log('req.url', req.url)

leof240 avatar Oct 25 '24 12:10 leof240

@leof240 Hey Leof 👋

Any chance you got that code handy? I'm currently experiencing an almost identical issue except my uri is getting encoded twice around my slug. So, I'm getting %255B instead of %5B... incredibly frustrating.

Using Next v13.5.6.

Appreciate any help!

seems that you are adding a "%" symbol to the request url (the % gets trunslated to %25

leof240 avatar Oct 25 '24 12:10 leof240

Code updated onto the branch "Fixed"

leof240 avatar Oct 25 '24 12:10 leof240

Thanks, @leof240 ! Got the same problem with an @ in parallel routes, like app/@modal/... Has always been crashing on production in Google App Engine Standard Environment but has been working fine locally on dev. So I adapted your solution with the following extra line:

.replaceAll('@', '%40')

That made it work. Leaving it here for anyone who has a Chunk Load Error with parallel routes on Google App Engine.

herrspiess avatar Apr 07 '25 20:04 herrspiess

I ran into a similar issue when upgrading our company's app from next 13.4.12 pages router to 15.3.3 pages router . But our issue was somewhat related to our NGINX reverse proxy, however I believe Next should have handled it.

Our app makes use of a catch all dynamic route like: [...uid]

Image

When a chunk is created for this route it is saved with a file name like this: '[...uid]-4d908551bf6ada7d.js' in .next/static/chunks/pages

Now when the browser makes a request to the server to GET these assets, the URL is percent encoded:

Image

When this request makes it way to NGINX , NGINX takes that percent encoding and turns something like %5B...uid%5D into %5b...uid%5d and then proxies that to our Next app. Next then doesn't recognize that request URL due to case sensitivity, and returns a 404.

At first I believed this to be a NGINX issue but realized that percent encoding is not case sensitive, per RFC 3986 . So it was still technically correct and Next should be able to handle.

My Solution was very similar to @leof240 's. In my Next middleware I check the request URL for lowercase encoding and replace it with uppercase encoding then rewrite.


  const isStaticAsset = request.url.includes('_next/static');
  const hasLowercaseBrackets = request.url.includes('%5b') || request.url.includes('%5d');

  if (isStaticAsset && hasLowercaseBrackets) {
    const url = request.nextUrl.clone();

    url.pathname = url.pathname
      .replaceAll(/%5b/g, '%5B')
      .replaceAll(/%5d/g, '%5D');

    return NextResponse.rewrite(url);
  }

I also had this issue when trying to upgrade to the the latest patch version of 13.4, and after reading through this issue: https://github.com/vercel/next.js/issues/54008#issuecomment-1734545438 . I believe the issue was introduced in 13.3.13

HermanDhillon avatar Jun 10 '25 16:06 HermanDhillon

@HermanDhillon How did you configure the middleware matcher? I'm experiencing this issue with the App Router on v15.3.4.

paigekim29 avatar Jun 20 '25 10:06 paigekim29

Funny enough on version 14, everything seemed to work but after upgrading to "next": "^15.3.4" i get chunk error when i try to access a page with parallel route defined:

Uncaught ChunkLoadError: Loading chunk 4997 failed. (error: https://.../_next/static/chunks/app/%5Blng%5D/flawis/%40sidebar/users/page-b89a5d24f6b7dd0e.js) at r.f.j (webpack-efa7c1ca77214fbd.js:1:3712)

i also have middleware config like so

export const config = { matcher: [ "/((?!api|_next|favicon.ico|apple-icon|images|UKsans|manifest.webmanifest|sw.js|.pdf).*)", ], };

I tested routes that do not have defined parallel routes and those render fine. But as soons as there is a parallel route returning something it renders at first for a split second but then breaks with the client side chunk error. It seems that there might be some sort of problem with the @ syntax of the folder name. Also all this happens only when running in production with npm run start, dev mode works just fine.

Could someone explain to me what the problem is please? Thanks in advance.

BobbiSixkiller avatar Jun 24 '25 07:06 BobbiSixkiller

I resolved my problem by configuring my apache web server reverse proxy like so

AllowEncodedSlashes NoDecode — allows URLs like %40sidebar (encoded @) ProxyPass / http://127.0.0.1:3000/ nocanon — prevents Apache from decoding percent-encoded URLs before proxying to Node/Next.js

BobbiSixkiller avatar Jun 24 '25 11:06 BobbiSixkiller

@paigekim29 Before the fix My matcher config looked like this:

export const config = {
  matcher: ["/", "/((?!_next/static|_next/image|images/|api/|favicon.ico|robots.txt).*)"],
};

This basically acts as a reverse matcher and ignores routes that match the regex

But in order to catch requests for static assets and rewrite them I had to remove the portion for "_next/static" and my matcher now looks like this:

export const config = {
  // normally '_next/static' was part of the exclude regex but was removed for the URI Encoding Fix
  matcher: ["/", "/((?!_next/image|images/|api/|favicon.ico|robots.txt).*)"],
};

I would have preferred to fix this whole issue via The Nginx and/or Apache config, but in my case that wasn't an option due to our host limiting access to those.

HermanDhillon avatar Jun 24 '25 15:06 HermanDhillon

I think this issue from next-intl might be related. https://github.com/amannn/next-intl/issues/255

I had this issue with client rendered parallel routes in relation to the next-intl middleware. I'm not sure, if this is really the same root cause as this one here. Please give me a hint, if I'm on the right track.

I created a repo to describe and reproduce the issue and provide demos for the issue and my workaround: https://github.com/davemecha/nextjs-parallel-routes-crash-mcve

I worked around the issue with a rewrite rule to revert the decoding of the slot url:

const nextConfig: NextConfig = {
  rewrites: async () => ({
    beforeFiles: [
      {
        source: '/_next/static/chunks/app/:folder*/@:slotName/:path*',
        destination: '/_next/static/chunks/app/:folder*/%40:slotName/:path*',
      },
    ],
    afterFiles: [],
    fallback: [],
  }),
};

const withNextIntl = createNextIntlPlugin();
export default withNextIntl(nextConfig);

davemecha avatar Jul 12 '25 22:07 davemecha

I think this issue from next-intl might be related. amannn/next-intl#255

I had this issue with client rendered parallel routes in relation to the next-intl middleware. I'm not sure, if this is really the same root cause as this one here. Please give me a hint, if I'm on the right track.

I created a repo to describe and reproduce the issue and provide demos for the issue and my workaround: https://github.com/davemecha/nextjs-parallel-routes-crash-mcve

I worked around the issue with a rewrite rule to revert the decoding of the slot url:

const nextConfig: NextConfig = { rewrites: async () => ({ beforeFiles: [ { source: '/_next/static/chunks/app/:folder*/@:slotName/:path*', destination: '/_next/static/chunks/app/:folder*/%40:slotName/:path*', }, ], afterFiles: [], fallback: [], }), };

const withNextIntl = createNextIntlPlugin(); export default withNextIntl(nextConfig);

Huge thanks to you. Got this error randomly on GCP but not locally, this fixed it, and it's really clean.

Grandnainconnu avatar Jul 22 '25 17:07 Grandnainconnu