Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

lmartins's avatar

Using env variables in Javascript with different local/production values

I'm working on a application that is connected to Algolia. Because I'm working locally with test data, I need to connect my local install to a different Algolia index, so I'm using .env variable to set different keys for my local and remote installs. Then, in Javascript, I'm reading those values using process.env.MIX_ALGOLIA_APP_ID which sadly isn't enough as these values will still be compiled using my local values when running npm prod. How do you typically approach this? Thanks!

0 likes
2 replies
ejdelmonico's avatar
Level 53

Without Webpack config: I have a dev.js and aprod.js that are assigned based on the module requested by something like key.js. key.js would have:

// keys.js - figure out what set of credentials to return
if (process.env.NODE_ENV === 'production') {
  // we are in production - return the prod set of keys
  module.exports = require('./prod');
} else {
  // we are in development - return the dev keys!!!
  module.exports = require('./dev');
}

If using webpack: bring in dotenv and use it config to determine which file to use (.env.development or .env.production). It would look something like this:

process.env.NODE_ENV = process.env.NODE_ENV || 'development';

if (process.env.NODE_ENV === 'test') {
  require('dotenv').config({ path: '.env.test' });
} else if (process.env.NODE_ENV === 'development') {
  require('dotenv').config({ path: '.env.development' });
}

module.exports = env => {
    const isProduction = env === 'production';
  const CSSExtract = new ExtractTextPlugin('styles.css');

  return {
    blah, blah, blah
    
    plugins: [
        new webpack.DefinePlugin({
        'process.env.FIREBASE_API_KEY': JSON.stringify(
          process.env.FIREBASE_API_KEY
        ),
        'process.env.FIREBASE_AUTH_DOMAIN': JSON.stringify(
          process.env.FIREBASE_AUTH_DOMAIN
        ),
        'process.env.FIREBASE_DATABASE_URL': JSON.stringify(
          process.env.FIREBASE_DATABASE_URL
        ),
        'process.env.FIREBASE_PROJECT_ID': JSON.stringify(
          process.env.FIREBASE_PROJECT_ID
        ),
        'process.env.FIREBASE_STORAGE_BUCKET': JSON.stringify(
          process.env.FIREBASE_STORAGE_BUCKET
        ),
        'process.env.FIREBASE_MESSAGING_SENDER_ID': JSON.stringify(
          process.env.FIREBASE_MESSAGING_SENDER_ID
        )
      })
    ]
    }
};

And, there are another few ways to do it.

Please or to participate in this conversation.