andreighe
andreighe

Reputation: 301

Config Vars from Heroku and Webpack

How can I use config vars from heroku on my frontend? In dev mode I've used my .env file and dotenv-webpack but this doesn't work in production. So I've tried to use a custom plugin lilke this:

new webpack.DefinePlugin({
'process.env': {
'     api1': JSON.stringify(process.env.api1),
     'api2': JSON.stringify(process.env.api2),
  }
})

Still, this doesn't work. Any ideas how can I use config vars from heroku on my react frontend, what do i need?

Upvotes: 4

Views: 620

Answers (2)

andreighe
andreighe

Reputation: 301

I've managed to solve this in another way. I will let the code below:

in my webpack.config.js file I add externals:

 externals: {
     'Config': JSON.stringify(
     {
       API_KEY: process.env.API_KEY,
       APP_URL: process.env.APPLICATION_URL,
     })
  }

and then in my React files I import Config like that:

import Config from 'Config'

and i can use the variables like that:

<p>{Config.API_KEY}</p>

Upvotes: 0

Eslam Abu Hugair
Eslam Abu Hugair

Reputation: 1208

when your host service builds your application you can generate a file and store it as config, which will be bundled and shipped as apart from the front. so you have access to the environment vars just on the build process, so you can take advantage of that and store your needed vars and they will be preserved on the bundle for your future access (on the client-side).

for example on file on your app call apis-configs.js

const whatYouWant = ['api1','api2'];

export default ()=>{
 return Object.keys(proccess.env)
              .filter(key => whatYouWant.includes(key))
              .reduce((config,key)=>{
                 if(!config[key]) config[key] = proccess.env[key]
                 return config
               },{})
}

So this is a normal config file, but instead of exporting hard-coded values, we export computed ones from the environment.(on the build run-time)

Upvotes: 1

Related Questions