loading...
Cover image for How to Store a Long Private Key in Vercel's Environment Variables

How to Store a Long Private Key in Vercel's Environment Variables

cfofiu profile image Claudio F. Updated on ・1 min read

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-----
Enter fullscreen mode Exit fullscreen mode

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-----"}'
Enter fullscreen mode Exit fullscreen mode

and use it in the code as following:

const { privateKey } = JSON.parse(process.env.FIREBASE_PRIVATE_KEY')
Enter fullscreen mode Exit fullscreen mode

Peace!

P.S. Obviously this method doesn't only apply to Vercel, but to any other cloud provider.

Discussion

pic
Editor guide