'Retrieve env variables in Strapi plugin

I develop a Strapi local plugin but I'm unable to retrieve variable defined in my .env file at the root of my project. I try to load this value in my React component (plugins/myPluginName/admin/src/containers/HomePage/index.js).

I try with the global process module like that :

process.env.my_variable

But it returns undefined

Any ideas ?



Solution 1:[1]

Thanks @sunnyson on the strapi forum I found a solution. By default .env variables are not passed to the client-side. You need to customize webpack config.

To do so :

  1. Create a folder /admin at the root of your project then create a admin.config.js.
module.exports = {
  webpack: (config, webpack) => {
    // Add your variable using the DefinePlugin function
    config.plugins.push(
      new webpack.DefinePlugin({
        // ENVS that you want to use in frontend
        CUSTOM_VARIABLES: {
          variable1: JSON.stringify(process.env.variable1),
        },
      })
    );
    // Return the modified config
    return config;
  },
};
  1. In your react component you can use your env variables like that :
class HomePage extends React.Component {

 constructor(props) {
   this.state = {
   env: { CUSTOM_VARIABLES }
   }

  logEnv() {
  console.log(this.state.env.variable1)
  }

}

Solution 2:[2]

Apparently, the admin panel now supports dotenv variables.

Just prefix your .env variable with STRAPI_ADMIN_ and it'll be available using process.env.

For example, STRAPI_ADMIN_KEY in .env is available as process.env.STRAPI_ADMIN_KEY

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 Thibault Walterspieler
Solution 2 Shakti