josh
josh

Reputation: 135

Where should I put my API key references and env files in a Node.js app?

I know I shouldn't hardcode my api keys and my mongo URL directly in my app.js file. Where should I put them? Should I just put them in a file called config.js and then export that as a module, then require that in my app.js file? What's the best way to do so, so when I move to production I don't have to change anything?

Upvotes: 2

Views: 1416

Answers (2)

Manu Artero
Manu Artero

Reputation: 10263

  • I'd go with config module. It's a simple lib which loads the proper json file according with your NODE_ENV value. For example, if you specify NODE_ENV=development npm start it'll load development.json and so on.

  • Another possibility: define a folder in your system outside your project folder and load your json files from there. For example, if you define /etc/opt/my-project-configs/ you would create that folder in your local system and in your pre/pro servers. Your code wouldn't know which environment is actually running but will load the proper config file.

Upvotes: 1

FastTurtle
FastTurtle

Reputation: 1787

In your config.js file you can do something like

module.exports = {
  accessKeyId: process.env.SES_ACCESS_KEY_ID
}

now put your keys in environmemt by using following command on terminal

export env.SES_ACCESS_KEY_ID='yourSecretKey'

now to use the setting do

var config = require('relativ/path/to/config.js');
someFunction(config.accessKeyId);

hope it helps :)

Upvotes: 1

Related Questions