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).
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: {
my_variable1: JSON.stringify(process.env.my_variable1),
my_variable2: JSON.stringify(process.env.my_variable2),
},
})
);
// Important: return the modified config
return config;
},
};
Unless the environment information is passed during the build time, you will need to create a backend route that your plugin frontend can request, the default route created if you used the plugin generator is the / index route that you can add a response from the Strapi backend to.
My goal is to make HTTP request outside of strapi from my plugin front-end and to do it I need to add x-api-key which is stored in my .env.
Is there a better way @DMehaffy ?
Unfortunately not, I would imagine you don’t want that API leaked in the build and it would be better in your case I think to construct an API controller in the plugin backend to handle the request and forward the response to your plugin frontend.
If the key environment variable isn’t included during build time (of the admin and the plugin admin) the frontend won’t be able to access the variable. The only other method is to request it from the Strapi backend or have the backend make the request.
Our admin is React based and thus is CSR (Client Side rendered) meaning once it’s built Strapi is only acting as a static web server for the built files.
Rename ./src/admin/webpack.config.example.js to ./src/admin/webpack.config.js.
Add the webpack.EnvironmentPlugin, which reads from the current process.env and assigns then to frontend, my full file is below.
"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
config.plugins.push(
new webpack.EnvironmentPlugin(["NODE_ENV", "TEST_VAR"])
);
// Important: return the modified config
return config;
};
From my react code, I can access the variables from the same path from my .env file.