How do I use environment variables or mask secrets in package.json?

Viewed 916

Here's an excerpt from my package.json file:

"scripts": {
    "start": "cross-env NODE_ENV=prod npx ./bin/www",
    "migrate": "node-pg-migrate",
    "migrate_dev": "DATABASE_URL=postgres://username:password@localhost:5432/dev_db NODE_ENV=dev node-pg-migrate",
  },

I'm excluding my .env file in .gitignore to ensure my secrets don't leak into the git repo. What I want to know is, what's the best way to deal with the username:password part of the migrate_dev script?

(And I've taken a look at this, but I'm pretty sure I can't use a .js file as a package.json stand-in.)

I tried assigning environment variables to environment variables, e.g.

"scripts": {
    ...
    "migrate_dev": "DATABASE_URL=DEV_DB_URL NODE_ENV=dev node-pg-migrate",
    ...
  },

but, sadly they aren't defined at this point - #bootstraps! ;-)

1 Answers

How do I use environment variables or mask secrets in package.json?

I'm excluding my .env file in .gitignore to ensure my secrets don't leak into the git repo.

Because your secrets are in your .env file, they can only be accessed programmatically, and package.json does not have that capability on its own. This would require a .js file.

You can run a .js file (i.e. migrate_dev.js) from your migrate_dev script:

"migrate_dev": "node migrate_dev.js"

Inside migrate_dev.js you should have access to your.env file and node-pg-migrate's Programmatic API (its CLI equivalent for JS):

https://salsita.github.io/node-pg-migrate/#/api

Related