Use .env in local plugin

Hello,

This is not how the frontend works. .env variables are not passed to the client-side.

To pass env variable to the administration panel you should customize webpack config,

1. create the file at the following route:

{strapi-project}/admin/admin.config.js:

module.exports = {
  webpack: (config, webpack) => {
    // Add your variable using the DefinePlugin
    config.plugins.push(
      new webpack.DefinePlugin({
        //All your custom ENVs that you want to use in frontend
        CUSTOM_VARIABLES: {
          my_variable1: JSON.stringify(process.env.my_variable1),
          my_variable2: JSON.stringify(process.env.my_variable2),
        },
      })
    );
    // Important: return the modified config
    return config;
  },
};

2. Add variables to .env

{strapi-project}/.env:

my_variable1=test_variable1
my_variable2=test_variable2

3. In React components, you can use them like this:

{CUSTOM_VARIABLES.my_variable1}

image

5 Likes