Most of the time you store simple, straight forward private keys for your deployments, but sometimes your project requires some complex ones like this one below.
-----BEGIN PRIVATE KEY-----
MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCt95m8QfrcIR+o
0a7S1hTtcbt7NhEJLiVELktu1XsFSitazhwvrRuVGn1c+cqgQbmAp7x/xoaYcLfY
tAaKR9v1xNEIBEwA/h1k+TFl7xJqH6Q07LBVYR0kVWiXgUHo6XWhlJEy4PCC5Yqo
eV2ZsA4Jjsh8c0cWTEFX9cCCT8cRIOfMeR/TcAeF/bPEOnmrbJJLV+5ivJUCHpio
[...]
tQeRV0IfFdnW8V3y6XI+xFYBOkx7D4BGFF8fUNr0iYMCWvICu2cJlWqi6Qmlk+LJ
br9Sl3Y2c1bXQbsW2ZKQJTANKBxeY1i9Au1pdCUCgYEAzbqB5omxKXcXx/0ZI/ao
cIJ9hQ6S18JIniG7DFyyUzqHansnqD1Qqxefl1fFLcuWktUivfbr7v5FoWUjwKLQ
JOJOVI3DZCsOumPrpEpjRa4cCQEjNPqYHL4voIR5IHRr+4iKSVrXUcmhdyqxjonG
11Avbqh479wA4VYksAF9AM4=
-----END PRIVATE KEY-----
When your project is ready to launch, but you're getting stuck in a few minor, silly errors like Failed to parse private key: Error: Invalid PEM formatted message
, you know that the problem is how the environment variable is stored, but have tried a lot of things to try to get it to work.
Well... hoping to save someone some time, I've ran across this pretty elegant solution in GitHub.
Store your multi-line Private Key like this:
FIREBASE_PRIVATE_KEY='{"privateKey":"-----BEGIN PRIVATE KEY-----\nMIIEvQIBADANBgkqhkiG9w0BAQE...-----END PRIVATE KEY-----"}'
and use it in the code as following:
const { privateKey } = JSON.parse(process.env.FIREBASE_PRIVATE_KEY)
Peace!
Top comments (6)
Hi Claudio, thank you for the post!
I'm still facing an issue, where the variable is not being read correctly from the environments variables set through Vercel's UI.
I'm getting:
this is because the key is undefined or sort of
Fixed it removing the single quotes wrapping the string.
It's all working perfect now, thank you!!!
Still facing the issue
JSON.parse: unexpected character at line 1 column 1 of the JSON data
My key is in the .env.local file
and I'm retrieving it like this
Hi! old thread here, but in case it helps, this solution worked for me for entering our Google Cloud Credentials in our Next Js project, but with the following adjustments:
\n
at the end of all the lines (including the last one). And created a long string with them. Just in case, use a JSON validator to be sure that your key is properly formatted.Thank you @cfofiu for the main approach to this.
Still having no luck with this.
Hi,
another way to store your multiline key is using the multiline string type (backticks)..`...
BACKTICKS = `
Example :
RSA_PKEY=(BACKTICKS)..............YOUR KEY..............(BACKTICKS)