How to access .env variables

I solved this by adding a custom webpack configuration to enable Strapi’s admin frontend to access the environment variables as global variables.

I renamed ./src/admin/webpack.example.config.js to ./src/admin/webpack.config.js. Refer to the v4 code migration: Updating the webpack configuration from the Official Strapi v4 Documentation.

I then inserted the following code, with help from Official webpack docs: DefinePlugin | webpack :

// ./src/admin/webpack.config.js
'use strict';

/* eslint-disable no-unused-vars */
module.exports = (config, webpack) => {
  // Note: we provide webpack above so you should not `require` it
  // Perform customizations to webpack config
  // Important: return the modified config
  config.plugins.push(
    new webpack.DefinePlugin({
      CLIENT_FRONTEND_URL: JSON.stringify(process.env.CLIENT_FRONTEND_URL),
      CLIENT_PREVIEW_SECRET: JSON.stringify(process.env.CLIENT_PREVIEW_SECRET),
    })
  )

  return config;
};

I rebuilt my app afterwards and it worked.

2 Likes