'How to set buildId to config (publicRuntimeConfig) or environment variable?

We're using nextjs (9.5.3) and next-i18next (6.0.3) for translations. To implement a special caching, I need to access the build ID outside of next.config.js in i18n.js in order to set it to the locale path:

localePath: path.resolve(`./public/static/cache/${config.buildId}/locales`)

In next.config.js I can access the build ID pretty easily:

withPWA({
  webpack(config, { buildId }) {
    [...]
    config.plugins.push(
      new CopyWebpackPlugin({
        patterns: [
          {
            context: path.join(__dirname, 'public/static/locales'),
            from: '**/*',
            to: path.join(__dirname, `public/static/cache/${buildId}/locales`)
          }
        ]
      })
    );
    // not working:-(
    process.env.CONFIG_BUILD_ID = buildId;
    return config;
  },
  publicRuntimeConfig: {
    buildId: process.env.CONFIG_BUILD_ID
  }
});

However setting it to the environment variable process.env.CONFIG_BUILD_ID is not working, so publicRuntimeConfig.buildId will still be undefined.

Is there any way to access the build ID outside the next config?



Solution 1:[1]

Instead of

// not working:-(
process.env.CONFIG_BUILD_ID = buildId;

You should use Webpack DefinePlugin (https://webpack.js.org/plugins/define-plugin/). No extra imports or installs are needed: this plugin is already a part of the next.js package. Just replace those lines with:

config.plugins.push(
    new webpack.DefinePlugin({
        'process.env.CONFIG_BUILD_ID': JSON.stringify(buildId)
    })
);

Full next.js.config may look like this:

/** @type {import('next').NextConfig} */
const nextConfig = {
  reactStrictMode: true,
  webpack: (config, { buildId, dev, isServer, defaultLoaders, webpack }) => {
    config.plugins.push(
      new webpack.DefinePlugin({
        'process.env.CONFIG_BUILD_ID': JSON.stringify(buildId)
      })
    );
    return config;
  }
}

module.exports = nextConfig;

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Andrii Kovalevskyi