Table of contents
This is a guide to setting up Routing Controllers (a very simple npm package to run an express server) with MongoDB.
I have a guide on setting up routing-controllers from scratch here.
If you have now set up your Routing Controllers application, you probably now need to configure it with environment variables (e.g. to connect to a database).
An easy way to set this up with with dotenv
.
First install dotenv as a dependency
Install dotenv
(yarn add dotenv
) to your package.json
Create a .env file
For local development you will probably want to use .env
file.
First: add it to your gitignore:
# in your .gitignore file
.env
And then create a file in your root directory called .env
, with some environment variables. In this case we are going to define a port number to use:
ROUTING_CONTROLLERS_PORT=4012
Load your env vars
In your routing-controllers
server setup file, add this:
import 'dotenv/config' // << just add this
/*
if you are doing cjs import with require() then it should be this:
require('dotenv').config()
*/
const PORT = process.env.ROUTING_CONTROLLERS_PORT || 4000;
console.info(`Starting server on http://localhost:${PORT}`);
Use it on production
In your production app you shouldn't use .env files, but proper environment variables. You can set these up in your normal way (depending on how you are hosting your app) and dotenv will pick them up.
Read more about dotenv
Before you use this on a real application I'd recommend you read the documentation for dotenv as there are lots of features you should be aware of.
Comments →Using environment variables (env vars/.env file) with Routing Controllers