Create a .env file in your backend folder
It should be in the root of the folder. It will be an empty file at first, but this will be where you store all your secrets.
Create a .gitignore file and add .env to it
This, again, should be in the root of your backend folder. Add, at the very least, .env
to it. It can (and should) contain more - everything you don’t want to push to a git repository.
Here’s an example of what a .gitignore could look like:
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
pnpm-debug.log*
lerna-debug.log*
node_modules
dist
dist-ssr
*.local
# Editor directories and files
.vscode/*
!.vscode/extensions.json
.idea
.DS_Store
**/.DS_Store
*.suo
*.ntvs*
*.njsproj
*.sln
*.sw?
.env
Store your .env variables
Now that we have secured our .env and it won’t be pushed to git we can add our environment variables in.
This is done, as we did with Vite, using a key value pair.
Variables are, by convention, written in all caps and snake case.
For example:
MONGO_DB_CLUSTER_NAME='this.is.your.cluster.name'
Reference .env variables in your code
In Node.js, in order to pull those variables in we’ll need to use a module called dotenv
.
Install it:
npm i dotenv
Then import it into whatever file you want to reference environment variables in using:
import dotenv from "dotenv"
dotenv.config()
The syntax we use is process.env.[VAR NAME]
to reference our environment variables in our code.
Using the example above, that would look like:
process.env.MONGO_DB_CLUSTER_NAME