-1

I have used express-generator to create a skeleton website and a template to work on. I do not know where to store sensitive information such as Data_config key, JWT secret, Connection URI, etc. Is there a workaround?

This is my current file tree. ./bin/www has the main server.js

I have previously used the dotenv package, but this is the first time I am using express-generator. I tried the same procedure by adding a .env file, and requiring dotenv by require('dotenv').config(), but it gives me an error.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
melarKode
  • 87
  • 1
  • 10
  • Related, from 2018 (but not a canonical either): *[Node.js - Storing password in env variable](https://stackoverflow.com/questions/53786224/)*. There must be a much older canonical question somewhere. Where is it? – Peter Mortensen May 30 '22 at 10:45
  • Related (where storing in environment variables was also suggested): *[How can I securely store the IP address, username and password of a database using Node.js?](https://stackoverflow.com/questions/52580754/)* – Peter Mortensen May 30 '22 at 10:57
  • A now-deleted answer is the subject of [a meta question](https://meta.stackexchange.com/questions/379126/is-it-more-important-that-answers-be-curated-than-accurate). – Peter Mortensen May 30 '22 at 10:57
  • Some leads (not about Node.js specifically, but one has *"Where do I store the private key?"*): *[Two-way encryption: I need to store passwords that can be retrieved](https://stackoverflow.com/questions/5089841/)* and *[How should I ethically approach user password storage for later plaintext retrieval?](https://stackoverflow.com/questions/2283937/)* – Peter Mortensen May 30 '22 at 10:59

2 Answers2

5

A good practice regarding environment variables is storing them in an environment (.env) file, which in Node.js you can access using the dotenv npm package.

This allows to avoid pushing sensitive data to versioning systems like Git or SVN and adds flexibility to use several instances of an application, which can represent ease of deployment and configuration for development pipelines.

dotenv in npm: https://www.npmjs.com/package/dotenv

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
rolivencia
  • 153
  • 8
2

You can include sensitive information at startup using environment variables. Start your application with the command below (or edit your startup script if you have one):

JWT_SECRET=secret node index.js

The JWT_SECRET variable can now be accessed in your application using the following code:

const JWT_SECRET = process.env['JWT_SECRET']

This will allow you to include your sensitive data in a startup script rather than being hard coded in the application. You can include multiple variables on startup as well. For example:

JWT_SECRET=secret CONNECTION_URI=http://localhost node index.js
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
mprather
  • 170
  • 1
  • 1
  • 8