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 :

  1. Navigate to the root level of your project and run:
    npm install dotenv
  2. Create a .env file at the root level of your project:
    touch .env
  3. Open that file in your code editor and fill in your secrets like:
    API_KEY=J8efk284jjfn9404595505849
    URL=http://www.somesite.fun
    username=literallyYOLO
    password=1234

    Of course, you will use your own credentials that you will use during your interaction with the browser rather than these phoney baloney ones.

  4. Then require dotenv either in your command line like
    node -r dotenv/config your_script.js

    OR in a file that would get run first

    const conf = dotenv.config()

Now your secrets are loaded into your process.env and you can access them like this: 

await page.click('#username', process.env.username);

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:

  1. Github username
  2. Github password
  3. Favorite Color
  4. 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

cannot read property username of undefined

.

Questions?

jscottchapman

About the Author

jscottchapman

Leave a Comment:

%d bloggers like this: