ok so first, you'll need to install a package called copy-webpack-plugin
:
npm install copy-webpack-plugin --save-dev
This package should allow you to customise the build process.
Next, in your next.config.js
file, you can add a custom Webpack configuration that writes your environment variables into a new .js
file and then copies it to your public
folder during the build process:
const CopyPlugin = require('copy-webpack-plugin');
const path = require('path');
const fs = require('fs');
module.exports = {
webpack: (config, { dev, isServer }) => {
if (!dev && !isServer) {
// The .js file you want to create
const fileContent = `const env = ${JSON.stringify(process.env)};`;
// The path of the file
const filePath = path.join(__dirname, 'public', 'env.js');
// Create the file
fs.writeFileSync(filePath, fileContent, 'utf8');
// Configure webpack to copy the file to the public folder
config.plugins.push(
new CopyPlugin({
patterns: [
{ from: 'public', to: '' },
],
})
);
}
return config;
},
};
One important thing to note here: by doing this, you're exposing all your environment variables to the client-side. Which is a bit risky if you've got any sensitive data in them. You'll probably want to adjust the fileContent
variable to only include the variables you need:
const fileContent = `const env = {MY_VAR: "${process.env.MY_VAR}"};`;
just so you're only exposing the variables you need in your public
folder. Replace "MY_VAR"
with the name of your environment variable.
Hopefully some of this helps