Next.js Error Getting 404 When Fetching JS Resources After Refresh

Viewed 14743

I'm running a Next.js dev server. When I go to page #1, then click a link to page #2, it works great. (Just to clarify, I'm not using the as prop of Next's <Link> tag, just the regular old href.)

However, if I then refresh page #2, the page itself loads, as do all the images ... but all of the Javascript files fail with a 404:

http://localhost:3000/page2/_next/static/chunks/main.js?ts=1612664646023 net::ERR_ABORTED 404 (Not Found) 2localhost/:196 GET

http://localhost:3000/page2/_next/static/development/_buildManifest.js?ts=1612664646023 net::ERR_ABORTED 404 (Not Found) 2localhost/:1 GET

http://localhost:3000/page2/_next/static/chunks/webpack.js?ts=1612664646023 net::ERR_ABORTED 404 (Not Found) 7localhost/:196 GET

http://localhost:3000/page2/_next/static/chunks/main.js?ts=1612664646023 net::ERR_ABORTED 404 (Not Found)

Does anyone know what I can do to fix this?

6 Answers

Ran into similar problem with inherited code, search a million times this was the top result. My answer for all other frustrated dev out there, check your 'Link' and your 'router.push()' especially if you are using a custom router. The Link and router.push() should be pointing to the server url. You can pass 'as' to mask the url for the browser.

Solved by removing assetPrefix: "." from next.config.js file.

This setting makes the assets path based on the current pages instead of the bath path url.

ie:

instead of: "test.com/_next/file.js"

it will be: "test.com/page/_next/file.js"

which obviously does not exist on that.

In our case we fixed it by skipping the next.js router for handling the URL:

  <Link
    onClick={() => {
      const url = '/path/to/url';
      Router.events.emit("routeChangeStart", url);
      window.location.href = url;
    }}
  >

I had the same issue but with npm run build on a React + Next JS template purchased from themeforest. It was because of the Next.js router, <Link> set up. This article helped me to fix the issue.

https://www.loudnoises.us/solving-next-static-pages-js-404-not-found/

The summary of the article is:

You’ll discover that the issue is that you did not create your components properly.

Here is what you probably did:

<Link
  href={`/articles/${uri}`}
>
  <a>
    Some text
  </a>
</Link>

Here is what you should have done:

<Link
  href={`/something-else?uri=${uri}`}
  as={`/articles/${uri}`}
>
  <a>
    Some text
  </a>
</Link>

For larger applications, add this to your next.config.js file

module.exports = {
  ...
  distDir: "_next",
  generateBuildId: async () => {
    if (process.env.BUILD_ID) {
      return process.env.BUILD_ID;
    } else {
      return `${new Date().getTime()}`;
    }
  },
  ...
}

It turned out that I had a problem in page #2's getStaticProps; once I fixed that the page worked again.

Related