javascriptnode.jsreactjsstrapi

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

  • 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)
      }
    
    }