How do I access environment variables or config from the front end?

I am setting a url in my environment variables. Let’s call it LOOKUP_URL.

How do I make it so that I can access LOOKUP_URL in my plugin? Specifically from the front end. The URL will be called in the admin area by the browser.

I have the following in my /src/admin/webpack.config.js:

module.exports = (config, webpack) => {
  const definePlugin = new webpack.DefinePlugin({
    LOOKUP_URL: "http://cheese.com"
  });

  config.plugins.push(definePlugin);

  return config;
};

Couldn’t you just use process.env.LOOKUP_URL

Not from the front end.

What about

var currentHost = window.location.host;

I’m not sure if it’s the same in Strapi v4, but in v3:

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: {
          CLIENT_URL: JSON.stringify(process.env.CLIENT_URL),
        },
      })
    );
    // Important: return the modified config
    return config;
  },
};

./src/admin/admin.config.js

Then in your frontend component:

const clientUrl = CUSTOM_VARIABLES.CLIENT_URL

Thanks for this, this really helped!

For anyone using TypeScript, you will need to declare the constant as a type. The easiest way to do this is to create a global.d.ts file in /src/admin/@types with the following:

declare const CUSTOM_VARIABLES: {
  CLIENT_URL: string;
};