Logo Xingxin on Bug

How to store JSON to an ENV variable?

May 22, 2025
2 min read

🤔Problem

While building my app dashboard, I wanted to use the Google Analytics Data API to fetch my website’s page views. To authorize the BetaAnalyticsDataClient(), I need a credential JSON like this:

{
  "type": "service_account",
  "project_id": "xxx",
  "private_key_id": "xxxxx",
  "private_key": "-----BEGIN PRIVATE KEY----- xxxxx -----END PRIVATE KEY-----\n",
  "client_email": "xxxxxxx@xxxx",
  "client_id": "xxxxxxxxx",
  "auth_uri": "xxxxxx",
  "token_uri": "xxxxxxx": "xxxxxxxx": "xxxxxxxxx",
  "client_x509_cert_url": "xxx",
  "universe_domain": "googleapis.com"
}

However, my website is deployed on Vercel and committing this JSON file directly into the repo is unsafe.

I then wondered how to store JSON in an environment variable? It turns out that it is very inconvenient. The reason is that when you decode back to JSON, the \n in the private_key causes headaches and is error-prone.

🔨Solution

Use the Base64 encoding!! Run this script to convert the credential into an encrypted Base64 string.

const fs = require('fs');
const credentials = fs.readFileSync('credentials.json', 'utf8');
const base64Credentials = Buffer.from(credentials).toString('base64');
console.log(base64Credentials);

Copy the console output (e.g. ew0KICAgICJ0...kg39=) and store it in an environment variable!

Now, you can easily decode and use it in your app:

const base64Credentials = process.env.GOOGLE_ANALYTICS_CREDENTIALS_64;
const credentialsJson = Buffer.from(base64Credentials, 'base64').toString('utf8');
const credentials = JSON.parse(credentialsJson);
const analyticsDataClient = new BetaAnalyticsDataClient({ credentials });

No more \n issues—just clean, secure credential handling! 🎉