Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access NextJS environment variables from inside the public folder

I have a custom .js file that I place inside the public folder in my NextJS app. I need to be able to use environment variables in that .js file, but environment variables don't seem to be available there.

I read that files in the public folder don't go through the webpack build process.

How do I customize my Next.js app so it builds an additional file inside the public folder? I found a suggestion (option 1 in the answer) on how to do it in a Vue.js app. Anyone know how to achieve something similar in Next.js?

like image 292
artooras Avatar asked Nov 17 '25 05:11

artooras


1 Answers

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

like image 141
luke Avatar answered Nov 20 '25 18:11

luke



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!