Skip to content

Instantly share code, notes, and snippets.

@amit08255
Last active April 2, 2025 18:07
Show Gist options
  • Save amit08255/a4eb51d5302e71ba3ecb267bc2a6a5e5 to your computer and use it in GitHub Desktop.
Save amit08255/a4eb51d5302e71ba3ecb267bc2a6a5e5 to your computer and use it in GitHub Desktop.
NextJS export cache issue fix. Update cache on every build

NextJS export cache issue fix. Update cache on every build

next.config.js file

/* the trick is to build unique build ID on every build and add it to static files on build time.
 * This way the name and URL of static files will change on every build.
 */

/* eslint-disable @typescript-eslint/no-var-requires */
const path = require('path');

// Used to set folders as alias to directly use in nextjs
const nextConfiguration = ({
    webpack: (config, { buildId, dev }) => {
        const newConfig = config;

        if (!dev && newConfig.output.filename.startsWith('static')) {
            newConfig.output.filename = newConfig.output.filename.replace('[name]', `[name]-${buildId}`);
            newConfig.output.chunkFilename = newConfig.output.chunkFilename.replace('[name]', `[name]-${buildId}`);
        }

        return newConfig;
    },
    generateBuildId: async () => {
        const timestamp = Math.floor(Date.now() / 1000);
        return `build-${timestamp}`;
    },
});

module.exports = nextConfiguration;
@ramseth001
Copy link

Hi @amit08255 How to update the names of files inside .next/static/css folder? The provided code is updating chunks folder files, but not css folder files

@suitux
Copy link

suitux commented Mar 5, 2025

Thanks a lot!

Cloudflare was caching the webpack chunk for every build because it had the same name...

Using NextJS 14.2.10

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment