How to write to Google Sheets asynchronously using NodeJS?

To create your NodeJS application connecting and writing to Google Sheets, you need to generate your authentication credentials.

  1. Go to Google Developer Console.
  2. Select or create a project.
  3. Navigate to the API libraries page here.
  4. Search for “Google Sheets API”, then click the “Enable” button to enable the Google Sheets API.
  5. Next, you need to generate OAuth client ID to use the API in code.
  6. Get one in your project’s credential page by clicking here. Go to the page -> Click “Create Credentials” -> “OAuth Client ID”
  7. It will open the “Create OAuth client ID” page, then choose the Other as we’re using this key in the node.js application.
  8. Finally, click on create. Now, your client ID and client secret will appear on a popup. Dismiss it.
  9. You should see a download button by now, click on it to download the credentials.
  10. Now, there will be a JSON file downloaded with credentials. Move the file to your project folder.

Install the required node packages by using the following command,

npm install google-auth-library –save 
npm install googleapis –save

Here’s an example of Google authentication I’m using in one of my projects,

Once the token is created, it will not ask again.

Update Google Sheet Asynchronously:

We need to authenticate every time before making a write operation to Google Sheet. So whenever a write operation is performed into a Google sheet, we need to go through an authentication step, so I’ve added an intermediate function doOperation().

Here’s how to call it from an external node file,

By now, you should be able to write the data to the sheet. Let me know what you think about this approach in the comments.

Leave a Comment

Your email address will not be published. Required fields are marked *