Back to APIs

Google Sheets

sheets.google.com

Read from and write to spreadsheets programmatically.

Using the Google Sheets 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 Sheets background job resumable and appear in our dashboard.

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

Use our HTTP endpoint to subscribe to webhooks

Example code using Google Sheets

Below are some working code examples of how you can use Google Sheets 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 { config } from "dotenv";
2
import { TriggerClient, eventTrigger } from "@trigger.dev/sdk";
3
import { google } from "googleapis";
4
import { JWT } from "google-auth-library";
5
import z from "zod";
6
7
// Create a service account and project: https://cloud.google.com/iam/docs/service-account-overview
8
// Create a JWT (JSON Web Token) authentication instance for Google APIs.
9
// https://cloud.google.com/nodejs/docs/reference/google-auth-library/latest/google-auth-library/jwt
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/spreadsheets", // The desired scope for accessing Google Sheets
14
});
15
16
// You have to enable the Google Sheets API: https://console.cloud.google.com/apis/
17
const sheets = google.sheets({ version: "v4", auth });
18
19
client.defineJob({
20
id: "google-sheets-append",
21
name: "Google Sheets Append",
22
version: "1.0.0",
23
trigger: eventTrigger({
24
name: "google-sheets",
25
schema: z.object({
26
fullName: z.string(),
27
githubUrl: z.string(),
28
range: z.string().optional(),
29
}),
30
}),
31
run: async (payload, io, ctx) => {
32
const { fullName, githubUrl, range } = payload;
33
34
// Wrap an SDK call in io.runTask so it's resumable and displays in logs
35
await io.runTask(
36
"Google Sheets append row",
37
async () => {
38
const sheetsData = [[fullName, githubUrl]];
39
40
const sheetsAPI = sheets.spreadsheets.values;
41
42
await sheetsAPI.append({
43
// NB: You must share your Google Sheet with your service account email
44
spreadsheetId: process.env.SPREADSHEET_ID,
45
// Set a spreadsheet range
46
range: range,
47
valueInputOption: "USER_ENTERED",
48
insertDataOption: "INSERT_ROWS",
49
requestBody: {
50
values: sheetsData,
51
},
52
});
53
},
54
55
// Add metadata to improve how the task displays in the logs
56
{ name: "Google Sheets append", icon: "google" }
57
);
58
},
59
});