Search code examples
dotenv

How to define array/object in .env file?


The following is my Javascript object:

window.options = {
    VAR1: VAL1,
    VAR2: VAL2,
    VA31: VAL3,
};

I want it (either object or array) to be defined in a .env file. How can I do that?


Solution

  • value in .env value can only be string.

    Simple workaround is to just store the env value as a comma separated value, like:

    SOME_VAR=VAL1,VAL2,VAL3
    

    and split it on your js file:

    const someVar = process.env.SOME_VAR.split(",");
    
    console.log(someVar); // [ 'VAL1', 'VAL2', 'VAL3' ]
    

    Or use whatever delimiter you want.


    If you want to store object, (unclean) workaround is to store JSON string as the env value, for example

    OBJECT_VAL={ "VAR1": "VAL1", "VAR2": "VAL2", "VA31": "VAL3" }
    

    and on your js code, you can parse the JSON:

    const objectVal= JSON.parse(process.env.OBJECT_VAL);
    console.log(objectVal); // { VAR1: 'VAL1', VAR2: 'VAL2', VA31: 'VAL3' }
    

    I personally don't think storing JSON string inside .env is a good idea, so I would like to give my recommendation on better way to store .env value and use it on your js code.

    1. Store env with normal string value, or delimiter separated value

    For example:

    ARRAY=VAL1,VAL2,VAL3
    
    VAR1=VALl1
    VAR2=VALl2
    VAR3=VALl3
    

    2. Make a js file to handle env variable

    I will call it env.js, and on this file I will export object containing all env variable

    module.exports = {
        array: process.env.ARRAY.split(","),
        object: {
           var1: process.env.VAR1,
           var2: process.env.VAR2,
           var3: process.env.VAR3,
        }
    }
    

    And on other file, you can just import env.js and call the env value

    const env = require("path/to/env.js");
    
    console.log(env.array); // [ 'VAL1', 'VAL2', 'VAL3' ]
    console.log(env.object.var1); // "VAL1"
    

    If your project often call process.env, this solution might make your code a bit cleaner since you don't need to call process. everytime you want to access your env variable.