'Firebaseapperror: failed to parse private key: error: invalid pem formatted message
I got this error firebaseapperror: failed to parse private key: error: invalid pem formatted message
when I pushed my nodejs app to heroku.
I had my environment variables all set like this
# .env file
project_id=project_id
private_key='-----BEGIN PRIVATE KEY----- ... ------END PRIVATE KEY-----\n'
client_email=client_email
And accessed them like so:
export const sa = {
privateKey: process.env.private_key,
projectId: process.env.project_id,
clientEmail: process.env.client_email
};
On my local everything worked fine, but on production (heroku) I got the error mentioned above. The private key is a multiline environment variable and it couldn't be parsed.
Please, how do I fix this?
Solution 1:[1]
The Fix
How I fixed this was through a post I saw online: How to Store a Long, Multi-line Private Key in an Environment Variable
Follow the step and you should fix this as well.
Brief summary of the post is this:
Store the long, multi-line key as a json string like this:
# .env file
project_id=project_id
private_key='{"privateKey": "-----BEGIN PRIVATE KEY----- ... ------END PRIVATE KEY-----\n"}'
client_email=client_email
Then parse it and destructure the key like this:
const { privateKey } = JSON.parse(process.env.private_key);
export const sa = {
privateKey,
projectId: process.env.project_id,
clientEmail: process.env.client_email
};
This would work on local, but on production (heroku) you will get a parse error because of the single quote before and after the very key in question. Therefore, remove the single quotes before and after the key in your production env variable. I also tried without the single quote on local and it worked.
Extra Benefit
Extra Benefit with this Method
From this, you could even store the entire environment variables as one object like this
# .env file
sa='{"privateKey": "-----BEGIN PRIVATE KEY----- ... ------END PRIVATE KEY-----\n", "clientEmail": "client_email", "projectId": "project_id"}'
Then access it like this:
export const sa = JSON.parse(process.env.sa);
That's it.
Reminder: remember what I said about single quote!
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 |