'What is the correct way to store a X.509 private key in an environment variable on Vercel and use it in Nextjs?
The Setup
I have a Nextjs app that uses Firebase Admin and requires a private key to initialize itself. It is a X.509 private key cert and to be safe I'm trying to store it in environment variables on Vercel - my hosting choice.
I have environment variables in a .env.local file as described in the nextjs documentation.
Since several places describe private keys stored "raw" not being stored properly by Vercel, but that they can be stored properly as JSON and later parsed by the app, I have done this.
Indeed testing storing the private key as is didn't work, and storing/parsing it in either of the two methods described on this github issue works locally with my variables in .env.local like so:
EXAMPLE_KEY=example_value
FIREBASE_PRIVATE_KEY='"-----BEGIN PRIVATE KEY-----\WdEFiwPk... ...htJthGef\n-----END PRIVATE KEY-----\n"'
The Problem
Trying to deploy these changes to Vercel has failed, and looking into why seems to point to environment variables stored in a wierd way on Vercel.
Using the Vercel cli to add a variable, and then supplying the text will always wrap the value supplied with double quotes:
If you vercel env add FIREBASE_PRIVATE_KEY and input true for the value,
And then run vercel env pull <filename>, the file will contain:
FIREBASE_PRIVATE_KEY="true"
This might not be a problem normally, but since the private key has double quotes wrapping it, submitting the value "raw" and then pulling it back to a local file looks like:
FIREBASE_PRIVATE_KEY=""-----BEGIN PRIVATE KEY-----\WdEFiwPk... ...htJthGef\n-----END PRIVATE KEY-----\n""
And trying to submit it in the JSON parse-able single quoted string returns:
FIREBASE_PRIVATE_KEY="'"-----BEGIN PRIVATE KEY-----\WdEFiwPk... ...htJthGef\n-----END PRIVATE KEY-----\n"'"
I thought that might just be how the data is formatted when pulled from Vercel, but it lines up with the error messages I was seeing from the app.
I've tried just about every combination and configuration to try and get a JSON.parse-able private key but can't seem to get it working. I even tried removing the double quotes wrapping the privateKey, seeing if the apparent added double quotes would be added and work there, but no dice.
Solution 1:[1]
Believe you can remove the --private-key--- section from the beginning and end, and just use the value in between.
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 | J Splits |
