next-images: dynamicAssetPrefix does not work as expected

I need to change CDN host after build when server starts. I try it with statically generated pages (using revalidate option of getStaticProps) and with dynamically generated pages. All urls change correct except urls to images which I import from js.

I have tried to use dynamicAssetPrefix. My next.config.js looks like this:

const withImages = require('next-images');
module.exports = withImages({
	assetPrefix: process.env.CDN,
	dynamicAssetPrefix: true,
	webpack(config, options) {
		return config;
	},
});

If I set CDN at build time then this CDN host still does not change when I change CDN env and start server.

And if I leave CDN env empty at build time then I get an error TypeError: Cannot read property 'nextImagesAssetPrefix' of undefined during build.

Is it a bug? or I do something wrong? What is a correct way to use dynamicAssetPrefix?

About this issue

  • Original URL
  • State: closed
  • Created 3 years ago
  • Comments: 15 (15 by maintainers)

Most upvoted comments

@peter-jozsa thanks for clarifying!

We really can’t use publicRuntimeConfig at statically generated pages but we can use serverRuntimeConfig at any pages during SSR. And inside a browser the __webpack_public_path__ variable is available. Next.js sets it at the client https://github.com/vercel/next.js/blob/master/packages/next/client/index.tsx#L73

So dynamicAssetPrefix can work everywhere with this code.

if (isServer) {
  return `(require("next/config").default().serverRuntimeConfig.nextImagesAssetPrefix || '') + ${p}`;
}

return `(__webpack_public_path__ || '') + ${p}`;

But there is one more thing. Next.js adds /_next/ to assetPrefix at the client when it sets __webpack_public_path__. So we need to add /_next/ to the publicPath only at the server or we get duplicate /_next/ at the client in a url.

I have tried to test it with as many case as possible. I have not found any problems.

@megazazik Wow nice, I checked your PR I think it makes sense and would solve this issue for sure. Thanks for your contribution, I have never used statically generated pages of Next.js good to have one here who has experience with it 😃