By Paul Scanlon

How to Use Google Application .json Credentials in Environment Variables

If youā€™ve ever tried to use one of Googleā€™s APIs youā€™ll know at some point youā€™re prompted to download the credentials as a .json file. This is super annoying because, as you probably also know, you canā€™t use objects in Node.js environment variables.

In this post iā€™ll show you one way to work around this which involves converting the giant .json object into a base64 string using your terminal.

Google Application Credentials

When setting up any kind of service account in Google youā€™ll eventually land on the below screen where youā€™ll be prompted to download your credentials.

Screenshot of Google Application credentials .json download

If you choose .json and open the file youā€™ll likely be looking at something similar to this.

Screenshot of VS Code .json file

Environment Variables in Node.js

But, you canā€™t use a .json object in your .env file, you have to use a string. E.g.

GOOGLE_APPLICATION_CREDENTIALS_BASE64="abc123"

The Solution

The solution iā€™ve been using is to convert the whole .json file into a base64 string and use that as the environment variable.

In the above screenshot the .json file is named: tns-weekly-analytics-4e9dfa8c536e.json. By running the following in my terminal iā€™ll be provided with a base64 string.

cat tns-weekly-analytics-4e9dfa8c536e.json | base64

Hereā€™s what the terminal output looks like.

Screenshot of terminal base64 string

Which can now be used in an .env file. E.g

GOOGLE_APPLICATION_CREDENTIALS_BASE64="ewogICJ0eXBlIjogInNlc..."

ā˜ļø Just make sure you wrap the string with double quotation makes!

Read base64 string in JavaScript

The last piece to the puzzle is how to read the base64 string from a .js file and use it with a Google Node.js client.

In this example iā€™m using google-analytics-data.

By defining a new const named credentials and using JSON.parse to create a Buffer.from the environment variable, then converting it back to a string with utf-8 encoding iā€™m able to use the newly created const when setting up the new BetaAnalyticsDataClient.

// src/some-js-file.js

import dotenv from 'dotenv';
dotenv.config();
import { BetaAnalyticsDataClient } from '@google-analytics/data';

const credentials = JSON.parse(
  Buffer.from(process.env.GOOGLE_APPLICATION_CREDENTIALS_BASE64, 'base64').toString('utf-8')
);

const analyticsDataClient = new BetaAnalyticsDataClient({
  credentials,
});

I had to do a fair amount of trial and error with this, not sure if itā€™s the best, or even the only way to achieve this, but it works!

The example iā€™ve shown is part of an article I published on The New Stack, which you can read here: How To Use GitHub Actions and APIs to Surface Important Data

If thereā€™s another way to achieve this, please let me know. This was a right ball ache!

Hey!

Leave a reaction and let me know how I'm doing.

  • 0
  • 0
  • 0
  • 0
  • 0
Powered byNeon