1

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 ?

2 Answers 2

5

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

Sign up to request clarification or add additional context in comments.

1 Comment

You are the best! It is not mentioned in the docs that having a prefix STRAPI_ADMIN will expose that var to admin frontend
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)
  }

}

2 Comments

It is throwing ReferenceError: CUSTOM_VARIABLES is not defined. Any idea what is causing this?
Deleting build folder and rebuilding the admin panel resolve this

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.