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
- Go to the Google Cloud Console and create a new project.
- Enable the Calendar API
- Create a service account
- 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")
- 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 (5)
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.
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/9824103Not adding a subject will result in an error "Service accounts cannot invite attendees without Domain-Wide Delegation of Authority."
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
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.
Have you found a sloution? I am encountering this issue too.