Using dotenv to store secrets in Puppeteer
Often you’re going to need to login to your mad decent app in order to interact with it or you may need to use an API key to get some info. Use dotenv or something like it to store your secrets. I first heard about how you shouldn’t store your secrets in your app from 12-factor app. Secrets? What? dotenv is super easy to use and it only has zero dependencies so there’s that.
The way you would use it in Puppeteer :
- Navigate to the root level of your project and run:
npm install dotenv
- Create a .env file at the root level of your project:
- Open that file in your code editor and fill in your secrets like:
Of course, you will use your own credentials that you will use during your interaction with the browser rather than these phoney baloney ones.
- Then require dotenv either in your command line like
node -r dotenv/config your_script.js
OR in a file that would get run firstconst conf = dotenv.config()
Now your secrets are loaded into your process.env and you can access them like this:
Important! Don’t forget to add your secrets to a .gitignore file. At the root level of the project create a file called .gitignore and then add the .env file into it and save it. Now, that file won’t be included in version control. In other words, you won’t accidentally publish your username and password to Github.
Another good idea is to go ahead and write in your README.md what your app will be expecting. Like:
This app will look for a .env file at the root level for the following credentials:
- Github username
- Github password
- Favorite Color
- And so on.
This way, if you pass the code on to someone else or make the code open source they won’t be left scratching their head when they get