next.js: Generated static files html files have wrong assets paths

Bug report

Describe the bug

I’m tried to generate a static site with Next js v9.0.2 and got assets linking by default to /_next/static/something/something.js. But by default build and export create a folder .next.

I think its related to: https://github.com/zeit/next.js/blob/4bcf6aabe7af477a8e58893f03622d84047abf2b/packages/next/pages/_document.tsx#L410

To Reproduce

  1. Create a static page
  2. Build it
  3. Open the html page generated
  4. See the source of every script inside the html page

Expected behavior

Generated path should begin with ./next/

Screenshots

Screen Shot 2019-07-29 at 12 25 54

System information

  • OS: macOS
  • Version of Next.js: 9.0.2

About this issue

  • Original URL
  • State: closed
  • Created 7 years ago
  • Reactions: 10
  • Comments: 34 (13 by maintainers)

Most upvoted comments

Thanks @cargallo 👍 Was trying to serve static exported files through an Electron app and was wondering why all the styles were missing. Post build-export find/replace will do for now.

[EDIT] After poking around a bit, there’s an attribute in the next.config.js called assetPrefix that lets you prefix a path to the static resources in the index.html (see https://nextjs.org/docs/api-reference/next.config.js/cdn-support-with-asset-prefix + https://github.com/vercel/next.js/pull/9916)

I’ve set my config to the following and it did the trick:

next.config.js

module.exports = {
  assetPrefix: ".",
};

Generated output: index.html

    <script
      src="./_next/static/SAfl4nj0fgiMC88TrHu7s/_ssgManifest.js"
      async=""
    ></script>

@cargallo if you haven’t done so already, you might want to use this instead of npm: replace-in-files-cli method 👍

DO NOT USE THIS SOLUTION ANY MORE !!! USE THE SOLUTION BELOW INSTEAD https://github.com/vercel/next.js/issues/8158#issuecomment-687707467

To automate the steps commented above:

yarn add --dev replace-in-files-cli

Then, add this two scripts in your package.json

"build-static": "next build && next export && npm run build-static-repair-index",

"build-static-repair-index": "replace-in-files --string \"/_next/static\" --replacement \"./_next/static\" out/index.html"

Then just call

npm run build-static

Explanation: The build-static-repair-index script will replace /_next/static with ./_next/static in the index.html file inside out folder wich is generated when you export your entire site to plain html wich can run standalone without any server.

Hope this helps. Reggards,

Hey folks. The issue being experienced by most of the comments above appears to be because once a next export is done and you have the out folder, if you serve the out folder under another folder, the urls to the assets will no longer resolve.

Imagine a basic project folder set up, something like:

My Project
--> pages
------> index.js
--> public
--> out

Then start an http server with the My Project folder as the root. The out folder from the browser url is then something like: http://localhost:8000/out/

The asset path Next.js uses ASSUMES that the out folder will be the root of your web server host.

Modifying the assetPrefix to “.” works for the above layout, but when you try to nest your pages any further it fails again.

e.g.

My Project
--> pages
------> index.js
------> login
----------> index.js
--> public
--> out

Now when you access http://localhost:8000/out/login/ the page is 404.

Modifying the trailingSlash option solves this so:

With a next.config.js of

module.exports = {
  assetPrefix: './',
  trailingSlash: true,
  reactStrictMode: true
}

But then, when you access http://localhost:8000/out/login/, the assets all try to load from http://localhost:8000/out/login/_next/***

The _next folder is assumed to be ./_next, relative to the current page URL path (/out/login), rather than the root of the out folder (/out).

Furthermore, client-side routing will work and render the pages but refreshing will 404 because the navigated URL changes from http://localhost:8000/out/login/ to http://localhost:8000/login/ when you click on a link client-side. /login doesn’t exist at the project folder root, only inside /out, as /out/login.

All of this is down to the relative vs absolute paths being used or not.

The question becomes, how do you configure Next.js to output HTML with paths that will operate without knowing ahead of time what folder or sub-folder they will be served from? I think many people commenting assume that the paths would take into account their position within the file tree when they are exported.

At the compile time it seems totally possible to know the relative path to the root of the _next folder from any page or component that might be using it but the URLs do not resolve that way at present unless I’m missing some config flag? I read the docs extensively to try and solve this one!

Essentially, at present as far as I can tell, you need to modify the config according to the place the code is going to be deployed (see basePath documentation). This seems pretty counterintuitive, although I realise that it is a non-issue for Vercel since they are deploying to known root paths in all cases.

I don’t understand how more people are not complaining about this. @cargallo - thank you for the work around 👍

well, like every one else I had faced this issue of wrong assets paths and it did not get solved by adding . to start of the string. I realized that I need to remove the / from the start of the path entirely. Thanks to @cargallo solution, I came up with my own script. So first you need to install the library: npm i --save replace-in-file Edit: The document of the library uses --save flag for installation but we don’t need to install this as a dependency in our next.js project. Use -D or --save-dev instead.

Then create a replacer.js at the root of your project and paste the below code in it:

const replace = require("replace-in-file");
const options = {
  //you may need to modify the file address to suite your project
  files: "./out/index.html",
  from: [/src="\//g, /href="\//g],
  to: ['src="', 'href="'],
};
(async function () {
  try {
    const results = await replace(options);
    console.log("Replacement results:", results);
  } catch (error) {
    console.error("Error occurred:", error);
  }
})();

Add the followings to your package.json "scripts":

"export": "next build && next export && npm run replaceFilePaths ",
"replaceFilePaths": "node replacer.js",

now, after runing the scripts you must be able to serve the out folder even from a different root.

Edit-2: as @peterDuot-stationfive mentioned it should be node replacer.js instead of node replaceInFiles.js.

@OHHAKO Sorry for the late reply.

Are you putting your image resources under ./public folder? (see https://nextjs.org/docs/basic-features/static-file-serving)

Example

When you layout the public folder like the following:

+ root
|
+ - public
       +
       |
      +- img
             +- red.jpg
             +- green.jpg
             +- blue.jpg
             +- none.jpg

Performing a “next build” + “next export”, the images will produce an out folder with:

+ root
|
+ - out
       +
       |
      +- img
             +- red.jpg
             +- green.jpg
             +- blue.jpg
             +- none.jpg

Then you can reference the images in your project like:

pages/index.js

const Home = () => {
   return (
      <div>
         <img src="/img/red.jpg" width={100} height={100} />
         <img src="/img/green.jpg" width={100} height={100} />
         <img src="/img/blue.jpg" width={100} height={100} />
      </div>
  );
}

export default Home;

OR via a component ./component/MyImage.js

const MyImage = (props) => {
  let { src, width, height } = { ...props };

  let uri = `/img/${src ?? "none"}.jpg`; // obviously add more error handling here to prevent folder traversal, but you get the gist!
  let w = width ?? 100;
  let h = height ?? 100;

  return <img src={uri} width={w} height={h} />;
}

export default MyImage;

./pages/index.js

import MyImage from "../components/MyImage"

const Home = () => {
   return (
      <div>
         <MyImage src="red" width={100} height={100} />
         <MyImage src="green" width={100} height={100} />
         <MyImage src="blue" width={100} height={100} />
      </div>
  );
}

export default Home;

NOTE

You will get an error if you attempt to use the inbuilt “next\Image” during an export

pages/index.js

import Image from "next/image"

const Home = () => {
   return (
      <div>
         <Image src="/img/red.jpg" width={100} height={100} />
         <Image src="/img/green.jpg" width={100} height={100} />
         <Image src="/img/blue.jpg" width={100} height={100} />
      </div>
  );
}

export default Home;

Error:

Error: Image Optimization using Next.js' default loader is not compatible with `next export`.
Possible solutions:
  - Use `next start`, which starts the Image Optimization API.
  - Use Vercel to deploy, which supports Image Optimization.
  - Configure a third-party loader in `next.config.js`.
Read more: https://err.sh/next.js/export-image-api

should be node replacer.js but I used this and it’s working in my local. Thank you 😃

It’s still happening! @spudmashmedia your advice really helpful to me. but it works only to specific element. (Doesn’t work to img tag path) thanks!

I don’t understand therefore what is next export command for? And it’s just easy to implement it has no sense at all.