Thank You nodemon, dotenv

Recently learned of two rather impactful updates in NodeJS that I don’t want to forget! As of recent versions, Node can now natively reference .env files, and restart the server when a file is updated. Before it was common practice to use the dotenv and nodemon packages to do each of these things, respectively. But now it comes out of the box!

How To Not Need dotenv

As of Node version 20.6.0 you can use the --env-file flag when starting the server and Node will access your environment variables directly. This video explains that the flag needs to come right after the node command. So with your .env file in the root directory, you could start your app like this:

$ node --env-file .env app.js

What worked in the video is different from the official documentation, so I’ll also include here instructions from the docs:

You can pass multiple –env-file arguments. Subsequent files override pre-existing variables defined in previous files.

node --env-file=.env --env-file=.development.env index.js 

This bypasses the need to import an extra package and removes a few lines of code. Awesome!

How To Not Need nodemon

As of Node version 18.11.0 you can use the --watch flag to replace the need for nodemon—Node will restart the server when any changes are saved in the watched file. Here’s another video demonstration, the docs, and the syntax:

$ node --watch app.js

Yay for needing less code and external packages!