Search code examples
javascriptcreate-react-appdotenv

Is it possible to use string literals in process.env values?


I would like to add an environment variables with parameters. something like:

URL= https://my-domain.com/test/${value}?code=7NqsdKgBKw

and calculate the value in js.

const value = Math.random();
fetch(process.env.URL);

how can I get the same effect as using literals?

const value = Math.random();
fetch(`https://my-domain.com/test/${value}?code=7NqsdKgBKw`);

Solution

  • For cases that are simple enough (no escaping, only one variable), Node.js has a built-in util.format with printf-style placeholders that’s nice and light:

    URL=https://my-domain.com/test/%s?code=7NqsdKgBKw
    
    // ESM: import { format } from 'util';
    const { format } = require('util');
    
    const urlFormat = process.env.URL;
    
    const value = Math.random();
    
    fetch(format(urlFormat, value))