Back to APIs

Google Calendar

calendar.google.com

Manage and automate calendar events, invites, and notifications.

Using the Google Calendar API with Trigger.dev

You can use Trigger.dev with any existing Node SDK or even just using fetch. Using io.runTask makes your Google Calendar background job resumable and appear in our dashboard.

Use io.runTask() and the official SDK or fetch.

Example code using Google Calendar

Below is a working code example of how you can use Google Calendar with Trigger.dev. These samples are open source and maintained by the community, you can copy and paste them into your own projects.

1
import { TriggerClient, eventTrigger } from "@trigger.dev/sdk";
2
import { google } from "googleapis";
3
import { JWT } from "google-auth-library";
4
import z from "zod";
5
6
// Create a service account and project: https://cloud.google.com/iam/docs/service-account-overview
7
// Create a JWT (JSON Web Token) authentication instance for Google APIs.
8
// https://cloud.google.com/nodejs/docs/reference/google-auth-library/latest/google-auth-library/jwt
9
// Make sure to add the service account email to the calendar you want to access as "Make changes to manage" https://support.google.com/calendar/answer/37082?hl=en
10
const auth = new JWT({
11
email: process.env.GOOGLE_CLIENT_EMAIL, // The email associated with the service account
12
key: process.env.GOOGLE_PRIVATE_KEY!.split(String.raw`\n`).join("\n"), // The private key associated with the service account
13
scopes: ["https://www.googleapis.com/auth/calendar"], // The desired scope for accessing Google Calendar
14
});
15
16
// Initialize the Google Calendar API
17
// You have to enable the Google Calendar API https://console.cloud.google.com/apis/
18
const calendar = google.calendar({ version: "v3", auth });
19
20
client.defineJob({
21
id: "google-calendar-event-create",
22
name: "Google Calendar Event Create",
23
version: "1.0.0",
24
trigger: eventTrigger({
25
name: "google-calendar",
26
schema: z.object({
27
calendarId: z.string(), // The calendar ID is in the Integrate Calendar section of the calendar settings
28
summary: z.string(),
29
description: z.string().optional(),
30
start: z.string(), // Format as ISO 8601 datetime string. Ex: "2021-08-01T12:00:00.000Z"
31
end: z.string(),
32
}),
33
}),
34
run: async (payload, io, ctx) => {
35
const { calendarId, summary, description, start, end } = payload;
36
37
// Wrap an SDK call in io.runTask so it's resumable and displays in logs
38
await io.runTask(
39
"Google Calendar create event",
40
async () => {
41
const requestBody = {
42
summary,
43
description,
44
start: {
45
dateTime: start,
46
timeZone: "UTC", // Adjust to the desired time zone
47
},
48
end: {
49
dateTime: end,
50
timeZone: "UTC",
51
},
52
};
53
54
await calendar.events.insert({ calendarId, requestBody });
55
},
56
57
// Add metadata to improve how the task displays in the logs
58
{ name: "Google Calendar create event", icon: "calendar" }
59
);
60
},
61
});