Node.js -Firebase Service Account Private Key won't parse

The problem was since I used dotenv variables inside the .env file the FIREBASE_PRIVATE_KEY had escaping characters: \n inside of it.

I had to follow this answer and append .replace(/\\n/g, '\n') to the end of it to parse it:

privateKey: process.env.FIREBASE_PRIVATE_KEY.replace(/\\n/g, '\n')

So now the code looks like:

admin.initializeApp({
  credential: admin.credential.cert({
      projectId: process.env.FIREBASE_PROJECT_ID, // I get no error here
      clientEmail: process.env.FIREBASE_CLIENT_EMAIL, // I get no error here
      privateKey: process.env.FIREBASE_PRIVATE_KEY.replace(/\\n/g, '\n') // NOW THIS WORKS!!!
  }),
  databaseURL: process.env.FIREBASE_DATABASE_URL
});

You must add your key into double qoutes to allow expanded new lines option according with dotenv documentation.

You can check that option at Rules section in dotenv github.

https://github.com/motdotla/dotenv#rules

  FIREBASE_PROJECT_ID=wwwwwwww
  FIREBASE_CLIENT_EMAIL=xxxxxxxx
  FIREBASE_DATABASE_URL=yyyyyyyy
  FIREBASE_PRIVATE_KEY="-----BEGIN PRIVATE KEY-----\nzzzzzzzz\n-----END PRIVATE KEY-----\n"