DEV Community

Cover image for Create Google Calender Events using the Google API and Service Accounts in Node.JS
Pedro Hase
Pedro Hase

Posted on

Create Google Calender Events using the Google API and Service Accounts in Node.JS

If you ever wanted to create Google Calendar Events in NodeJS without having to use OAuth2 (and thus not having to ask users for their permissions), then this article is just for your.

To do so we will employee so-called Google Cloud "Service accounts" which allow to interact with the API as an application.

Setup

  1. Go to the Google Cloud Console and create a new project.
  2. Enable the Calendar API
  3. Create a service account
  4. In your calendar where you want to create events, go to the settings and share the calendar with the e-mail of your service account (Make sure to set the permissions to "Make changes to events")
  5. Create and save the credentials JSON for your created account into your Node.JS project

Code

First you need to install googleapis and google-auth-library in your Node.JS project. Then just plug in the function below to create a new event 🙂

Make sure that you set the calendar ID of the calendar where you want to create the events and that your downloaded credentials.json is in the right place.

P.S.: Using this approach you can also interact with any other Google Services. Just make sure that your service account has the right permissions and or that the APIs are enabled and the correct scopes are set 😉.

Top comments (4)

Collapse
 
reaganmac92 profile image
reaganmac92 • Edited

Thank you! I have been trying to figure this out all day and your post finally helped me, with the JWT authentication ⭐😁⭐

Edit to add: I stored the email and private key in environment variables, to prevent them from being checked in to source control and leaked to the public.

Collapse
 
sleepystar profile image
sleepystar

Great tutorial, thanks @pedrohase !

I do want to add that a subject: "real-user@gmail.com" key-value is needed in the JWT body if you are adding invitees to your event. References: stackoverflow.com/a/61932919/9824103

Not adding a subject will result in an error "Service accounts cannot invite attendees without Domain-Wide Delegation of Authority."

Collapse
 
__c8d4bb453140c17a804f profile image
敬峰 刘

I'm using the same code as described in the appeal, and the key is confirmed, but I'm still getting the error.

error message: Invalid response body while trying to fetch googleapis.com/oauth2/v4/token: read ECONNRESET

Collapse
 
rnydv3004 profile image
Aryan Yadav

I am using the same code , and the code is working perfectly on localhost but when I deploy it to the live server then it won't work.