0

I have a password. I don't want to commit it to the repo. I am writing tests with puppeteer. The logical thing to do would be to save the password in a file somewhere, git-ignore the file, then load it in puppeteer. But I'm not sure how to do that. Suggestions?

This is what I am trying. It doesn't work, yet:

file loadPassword.js:

import { config } from "dotenv";  // This appears in lightweight type in VS code, implying that VS code thinks the line is not doing anything.

console.log('getting password');
let pass = process.env.PASSWORD;
console.log('the actual password has been loaded into the variable "pass".');
console.log('the password is ', pass);
let foo = process.env['PASSWORD'];
console.log(foo);
// but when I run, both pass and foo print out as undefined.

file .env:

{
    PASSWORD: 'secret'
}

file package.json:

{
    "type": "module",
    "dependencies": {
        "dotenv": "^16.0.3",
        "puppeteer": "^19.8.3"
    }
}

To run, in terminal:

node loadPassword
William Jockusch
  • 26,513
  • 49
  • 182
  • 323
  • Does this answer your question? [Read environment variables in Node.js](https://stackoverflow.com/questions/4870328/read-environment-variables-in-node-js) – ggorlen Apr 05 '23 at 17:02
  • This appears to be unrelated to Puppeteer. The normal node approach is to create a `.env` file, add it to your `.gitignore`, put your secret in as `PASSWORD=secret`, then use [dotenv](https://www.npmjs.com/package/dotenv) to load it: `require("dotenv").config()`, then access it with `process.env.PASSWORD`. See [this answer](https://stackoverflow.com/a/49611972/6243352). – ggorlen Apr 05 '23 at 17:03
  • Not yet, require is throwing an exception. I tried 'import {config} from "dotenv";' instead, but the password is coming through as undefined, even though it is in the '.env' file. Trying to tweak it so it behaves. – William Jockusch Apr 05 '23 at 17:28
  • 1
    Could you update your post to show your code, dotenv version (or package.json), file contents and directory tree? I'll try to reproduce the problem locally. Thanks. – ggorlen Apr 05 '23 at 17:34

1 Answers1

-1

This works, but I'd still be interested in a better solution:

file .gitignore:

password.js

file password.js:

export function getPassword() {
    return 'secret';
}

file password.js.template:

export function getPassword() {
    return 'copy and paste this file to a file password.js, then put your actual password here in the copy.';
}

file loadPassword.js:

import puppeteer from 'puppeteer';
import { getPassword } from './password.js';

(async () => {
    console.log('getting password');
    let pass = getPassword();
    console.log('the actual password has been loaded into the variable "pass".')
})();

To run, in terminal:

node loadPassword
William Jockusch
  • 26,513
  • 49
  • 182
  • 323