How to deploy NodeJS application that’s using Google Sheets API (google-spreadsheet) on Heroku

Rahul Ravindran
2 min readDec 31, 2020

In this blog, we’ll learn how to deploy a NodeJS application that uses Google Sheets API under the hood. In most of the cases, the application runs in the localhost but when the application is deployed on Heroku, it crashes.

This blog is a continuation of the previous blog if some of the jargons used here are bouncing for you. Then I would recommend you to read the previous blog to get a hang of what’s going on here.

The reason

The main reason for the Heroku instance to crash is that the google-spreadsheet couldn’t authenticate the user properly. Why does this happen? Every worked on localhost !!

Good that you asked! The reason is that Heroku is looking at the env variable that contains the client_credentials.json value. Which we used to authenticate the user on localhost. But in production Heroku is not able to parse the JSON file, hence it crashes the entire application.

To solve this problem we’ve to encode the JSON file and pass the encoded value to the env variable in the production environment.

Installing the necessary packages

npm install utf8 base64

For simplicity, we’re using these packages to encode our files. You can do this in Vanilla JS too, it’s totally upon you.

Encoding the client_credentials.json file

let text = JSON.stringify(require('../json/client_secret.json'));
let bytes = utf8.encode(text);
let encoded = base64.encode(bytes);
console.log('base64 encode: ', encoded);

After running this script you’ll get long encoded text in the console. Copy that encoded base64 string and paste it as the value to the env variable in the Heroku dashboard.

Changing the index.js file to adapt to the new changes

...
encoded = process.env.GOOGLE_CREDENTIALS;
bytes = base64.decode(encoded);text = utf8.decode(bytes);await doc.useServiceAccountAuth(JSON.parse(text));...

Add the above 3 lines of code before we pass the credentials to the useServiceAccountAuth() function for authentication. The above lines of code will parse the base64 encoded string into a JSON readable file which can be used to authenticate the user successfully

--

--