Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

(node.js) how to use environment variables in JSON file

Tags:

node.js

I'm using a 3rd party library that needs a JSON config file, and I need to pass some env variables in as key values. If I include them as I normally would, eg:

  "s3": {     "key": process.env.AWS_ACCESS_KEY_ID,     "secret": process.env.AWS_SECRET_ACCESS_KEY,     "bucket": process.env.S3_MLL_BUCKET_NAME,     "destination": "/backups/database",     "encrypt": false,     "region": process.env.AWS_REGION   } 

...I get the error:

SyntaxError: config/s3_backup.config.json: Unexpected token p 
like image 227
Ben Avatar asked May 01 '16 03:05

Ben


People also ask

Can I use environment variables in JSON file?

You have to wrap the environment variable of choice into another set of quotes in order for it to be valid JSON.

What is env JSON?

The env. json file is a project-specific list of accessible variables. This file is the ideal place to store secret keys, project-wide properties, or anything else you want to obfuscate or share between your files.


2 Answers

JSON does not have notion of environment variables. What you can do though is to declare your configuration file as node.js module and then you will be able to use your environment variables as follows:

module.exports = {   s3: {     key: process.env.AWS_ACCESS_KEY_ID,     secret: process.env.AWS_SECRET_ACCESS_KEY,     bucket: process.env.S3_MLL_BUCKET_NAME,     destination: "/backups/database",     encrypt: false,     region: process.env.AWS_REGION   } }; 
like image 147
dtoux Avatar answered Oct 25 '22 15:10

dtoux


I had the same issue, what worked for me was using a js file and exporting an object module.exports = {config: {"exampleAPIKey":"ruier4343"}}...then "stringifying" the object and then parsing it back to json const config = require("./jsConfigs.js").config; const jsonConfig = JSON.parse(JSON.stringify(config)) I had tried it so many different ways but this is the only one that worked.

like image 21
Muganwas Avatar answered Oct 25 '22 15:10

Muganwas