-
-
Notifications
You must be signed in to change notification settings - Fork 1.2k
Expand file tree
/
Copy pathwriting-tasks.mdc
More file actions
1247 lines (956 loc) · 31.5 KB
/
writing-tasks.mdc
File metadata and controls
1247 lines (956 loc) · 31.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
---
globs: **/trigger/**/*.ts, **/trigger/**/*.tsx,**/trigger/**/*.js,**/trigger/**/*.jsx
description: Guidelines for writing Trigger.dev tasks
alwaysApply: false
---
# How to write Trigger.dev tasks
## Overview of writing a Trigger.dev task
1. Run the CLI `init` command: `npx trigger.dev@latest init`.
2. Create a Trigger.dev task.
3. Set up any environment variables.
4. Run the Trigger.dev dev command: `npx trigger.dev@latest dev`.
## Essential requirements when generating task code
1. You MUST import from `@trigger.dev/sdk` (NEVER `@trigger.dev/sdk/v3`)
2. You MUST NEVER use `client.defineJob`
3. YOU MUST `export` every task, including subtasks
4. If you are able to generate an example payload for a task, do so.
## 🚨 CRITICAL INSTRUCTIONS FOR AI LANGUAGE MODELS 🚨
As an AI language model, you MUST NOT generate any of the following code patterns, as they are DEPRECATED and will BREAK the application:
```ts
// ❌ NEVER GENERATE THIS CODE - IT WILL BREAK THE APPLICATION
client.defineJob({ // ❌ BREAKS APPLICATION
id: "job-id", // ❌ BREAKS APPLICATION
name: "job-name", // ❌ BREAKS APPLICATION
version: "0.0.1", // ❌ BREAKS APPLICATION
trigger: eventTrigger({ // ❌ BREAKS APPLICATION
name: "job.trigger", // ❌ BREAKS APPLICATION
schema: z.object({ // ❌ BREAKS APPLICATION
// Input schema here // ❌ BREAKS APPLICATION
}), // ❌ BREAKS APPLICATION
}), // ❌ BREAKS APPLICATION
integrations: { // ❌ BREAKS APPLICATION
// Integrations here // ❌ BREAKS APPLICATION
}, // ❌ BREAKS APPLICATION
run: async (payload, io) => { // ❌ BREAKS APPLICATION
// Job logic goes here // ❌ BREAKS APPLICATION
return { // ❌ BREAKS APPLICATION
// Return job results // ❌ BREAKS APPLICATION
}; // ❌ BREAKS APPLICATION
}, // ❌ BREAKS APPLICATION
});
```
Instead, you MUST ALWAYS generate ONLY this pattern:
```ts
// ✅ ALWAYS GENERATE THIS EXACT PATTERN
import { task } from "@trigger.dev/sdk";
//1. You need to export each task, even if it's a subtask
export const helloWorld = task({
//2. Use a unique id for each task
id: "hello-world",
//3. The run function is the main function of the task
run: async (payload: { message: string }) => {
//4. Write your task code here. Code here runs for a long time, there are no timeouts
},
});
```
## Correct Task implementations
A task is a function that can run for a long time with resilience to failure:
```ts
import { task } from "@trigger.dev/sdk";
export const helloWorld = task({
id: "hello-world",
run: async (payload: { message: string }) => {
console.log(payload.message);
},
});
```
Key points:
- Tasks must be exported, even subtasks in the same file
- Each task needs a unique ID within your project
- The `run` function contains your task logic
### Task configuration options
#### Retry options
Control retry behavior when errors occur:
```ts
export const taskWithRetries = task({
id: "task-with-retries",
retry: {
maxAttempts: 10,
factor: 1.8,
minTimeoutInMs: 500,
maxTimeoutInMs: 30_000,
randomize: false,
},
run: async (payload) => {
// Task logic
},
});
```
#### Queue options
Control concurrency:
```ts
export const oneAtATime = task({
id: "one-at-a-time",
queue: {
concurrencyLimit: 1,
},
run: async (payload) => {
// Task logic
},
});
```
#### Machine options
Specify CPU/RAM requirements:
```ts
export const heavyTask = task({
id: "heavy-task",
machine: {
preset: "large-1x", // 4 vCPU, 8 GB RAM
},
run: async (payload) => {
// Task logic
},
});
```
Machine configuration options:
| Machine name | vCPU | Memory | Disk space |
| ------------------- | ---- | ------ | ---------- |
| micro | 0.25 | 0.25 | 10GB |
| small-1x (default) | 0.5 | 0.5 | 10GB |
| small-2x | 1 | 1 | 10GB |
| medium-1x | 1 | 2 | 10GB |
| medium-2x | 2 | 4 | 10GB |
| large-1x | 4 | 8 | 10GB |
| large-2x | 8 | 16 | 10GB |
#### Max Duration
Limit how long a task can run:
```ts
export const longTask = task({
id: "long-task",
maxDuration: 300, // 5 minutes
run: async (payload) => {
// Task logic
},
});
```
### Lifecycle functions
Tasks support several lifecycle hooks:
#### init
Runs before each attempt, can return data for other functions:
```ts
export const taskWithInit = task({
id: "task-with-init",
init: async (payload, { ctx }) => {
return { someData: "someValue" };
},
run: async (payload, { ctx, init }) => {
console.log(init.someData); // "someValue"
},
});
```
#### cleanup
Runs after each attempt, regardless of success/failure:
```ts
export const taskWithCleanup = task({
id: "task-with-cleanup",
cleanup: async (payload, { ctx }) => {
// Cleanup resources
},
run: async (payload, { ctx }) => {
// Task logic
},
});
```
#### onStart
Runs once when a task starts (not on retries):
```ts
export const taskWithOnStart = task({
id: "task-with-on-start",
onStart: async (payload, { ctx }) => {
// Send notification, log, etc.
},
run: async (payload, { ctx }) => {
// Task logic
},
});
```
#### onSuccess
Runs when a task succeeds:
```ts
export const taskWithOnSuccess = task({
id: "task-with-on-success",
onSuccess: async (payload, output, { ctx }) => {
// Handle success
},
run: async (payload, { ctx }) => {
// Task logic
},
});
```
#### onFailure
Runs when a task fails after all retries:
```ts
export const taskWithOnFailure = task({
id: "task-with-on-failure",
onFailure: async (payload, error, { ctx }) => {
// Handle failure
},
run: async (payload, { ctx }) => {
// Task logic
},
});
```
#### handleError
Controls error handling and retry behavior:
```ts
export const taskWithErrorHandling = task({
id: "task-with-error-handling",
handleError: async (error, { ctx }) => {
// Custom error handling
},
run: async (payload, { ctx }) => {
// Task logic
},
});
```
Global lifecycle hooks can also be defined in `trigger.config.ts` to apply to all tasks.
## Correct Schedules task (cron) implementations
```ts
import { schedules } from "@trigger.dev/sdk";
export const firstScheduledTask = schedules.task({
id: "first-scheduled-task",
run: async (payload) => {
//when the task was scheduled to run
//note this will be slightly different from new Date() because it takes a few ms to run the task
console.log(payload.timestamp); //is a Date object
//when the task was last run
//this can be undefined if it's never been run
console.log(payload.lastTimestamp); //is a Date object or undefined
//the timezone the schedule was registered with, defaults to "UTC"
//this is in IANA format, e.g. "America/New_York"
//See the full list here: https://cloud.trigger.dev/timezones
console.log(payload.timezone); //is a string
//If you want to output the time in the user's timezone do this:
const formatted = payload.timestamp.toLocaleString("en-US", {
timeZone: payload.timezone,
});
//the schedule id (you can have many schedules for the same task)
//using this you can remove the schedule, update it, etc
console.log(payload.scheduleId); //is a string
//you can optionally provide an external id when creating the schedule
//usually you would set this to a userId or some other unique identifier
//this can be undefined if you didn't provide one
console.log(payload.externalId); //is a string or undefined
//the next 5 dates this task is scheduled to run
console.log(payload.upcoming); //is an array of Date objects
},
});
```
### Attach a Declarative schedule
```ts
import { schedules } from "@trigger.dev/sdk";
// Sepcify a cron pattern (UTC)
export const firstScheduledTask = schedules.task({
id: "first-scheduled-task",
//every two hours (UTC timezone)
cron: "0 */2 * * *",
run: async (payload, { ctx }) => {
//do something
},
});
```
```ts
import { schedules } from "@trigger.dev/sdk";
// Specify a specific timezone like this:
export const secondScheduledTask = schedules.task({
id: "second-scheduled-task",
cron: {
//5am every day Tokyo time
pattern: "0 5 * * *",
timezone: "Asia/Tokyo",
},
run: async (payload) => {},
});
```
### Attach an Imperative schedule
Create schedules explicitly for tasks using the dashboard's "New schedule" button or the SDK.
#### Benefits
- Dynamic creation (e.g., one schedule per user)
- Manage without code deployment:
- Activate/disable
- Edit
- Delete
#### Implementation
1. Define a task using `schedules.task()`
2. Attach one or more schedules via:
- Dashboard
- SDK
#### Attach schedules with the SDK like this
```ts
const createdSchedule = await schedules.create({
//The id of the scheduled task you want to attach to.
task: firstScheduledTask.id,
//The schedule in cron format.
cron: "0 0 * * *",
//this is required, it prevents you from creating duplicate schedules. It will update the schedule if it already exists.
deduplicationKey: "my-deduplication-key",
});
```
## Correct Schema task implementations
Schema tasks validate payloads against a schema before execution:
```ts
import { schemaTask } from "@trigger.dev/sdk";
import { z } from "zod";
const myTask = schemaTask({
id: "my-task",
schema: z.object({
name: z.string(),
age: z.number(),
}),
run: async (payload) => {
// Payload is typed and validated
console.log(payload.name, payload.age);
},
});
```
## Correct implementations for triggering a task from your backend
When you trigger a task from your backend code, you need to set the `TRIGGER_SECRET_KEY` environment variable. You can find the value on the API keys page in the Trigger.dev dashboard.
### tasks.trigger()
Triggers a single run of a task with specified payload and options without importing the task. Use type-only imports for full type checking.
```ts
import { tasks } from "@trigger.dev/sdk";
import type { emailSequence } from "~/trigger/emails";
export async function POST(request: Request) {
const data = await request.json();
const handle = await tasks.trigger<typeof emailSequence>("email-sequence", {
to: data.email,
name: data.name,
});
return Response.json(handle);
}
```
### tasks.batchTrigger()
Triggers multiple runs of a single task with different payloads without importing the task.
```ts
import { tasks } from "@trigger.dev/sdk";
import type { emailSequence } from "~/trigger/emails";
export async function POST(request: Request) {
const data = await request.json();
const batchHandle = await tasks.batchTrigger<typeof emailSequence>(
"email-sequence",
data.users.map((u) => ({ payload: { to: u.email, name: u.name } }))
);
return Response.json(batchHandle);
}
```
### batch.trigger()
Triggers multiple runs of different tasks at once, useful when you need to execute multiple tasks simultaneously.
```ts
import { batch } from "@trigger.dev/sdk";
import type { myTask1, myTask2 } from "~/trigger/myTasks";
export async function POST(request: Request) {
const data = await request.json();
const result = await batch.trigger<typeof myTask1 | typeof myTask2>([
{ id: "my-task-1", payload: { some: data.some } },
{ id: "my-task-2", payload: { other: data.other } },
]);
return Response.json(result);
}
```
## Correct implementations for triggering a task from inside another task
### yourTask.trigger()
Triggers a single run of a task with specified payload and options.
```ts
import { myOtherTask, runs } from "~/trigger/my-other-task";
export const myTask = task({
id: "my-task",
run: async (payload: string) => {
const handle = await myOtherTask.trigger({ foo: "some data" });
const run = await runs.retrieve(handle);
// Do something with the run
},
});
```
If you need to call `trigger()` on a task in a loop, use `batchTrigger()` instead which can trigger up to 500 runs in a single call.
### yourTask.batchTrigger()
Triggers multiple runs of a single task with different payloads.
```ts
import { myOtherTask, batch } from "~/trigger/my-other-task";
export const myTask = task({
id: "my-task",
run: async (payload: string) => {
const batchHandle = await myOtherTask.batchTrigger([{ payload: "some data" }]);
//...do other stuff
const batch = await batch.retrieve(batchHandle.id);
},
});
```
### yourTask.triggerAndWait()
Triggers a task and waits for the result, useful when you need to call a different task and use its result.
```ts
export const parentTask = task({
id: "parent-task",
run: async (payload: string) => {
const result = await childTask.triggerAndWait("some-data");
console.log("Result", result);
//...do stuff with the result
},
});
```
The result object needs to be checked to see if the child task run was successful. You can also use the `unwrap` method to get the output directly or handle errors with `SubtaskUnwrapError`. This method should only be used inside a task.
### yourTask.batchTriggerAndWait()
Batch triggers a task and waits for all results, useful for fan-out patterns.
```ts
export const batchParentTask = task({
id: "parent-task",
run: async (payload: string) => {
const results = await childTask.batchTriggerAndWait([
{ payload: "item4" },
{ payload: "item5" },
{ payload: "item6" },
]);
console.log("Results", results);
//...do stuff with the result
},
});
```
You can handle run failures by inspecting individual run results and implementing custom error handling strategies. This method should only be used inside a task.
### batch.triggerAndWait()
Batch triggers multiple different tasks and waits for all results.
```ts
export const parentTask = task({
id: "parent-task",
run: async (payload: string) => {
const results = await batch.triggerAndWait<typeof childTask1 | typeof childTask2>([
{ id: "child-task-1", payload: { foo: "World" } },
{ id: "child-task-2", payload: { bar: 42 } },
]);
for (const result of results) {
if (result.ok) {
switch (result.taskIdentifier) {
case "child-task-1":
console.log("Child task 1 output", result.output);
break;
case "child-task-2":
console.log("Child task 2 output", result.output);
break;
}
}
}
},
});
```
### batch.triggerByTask()
Batch triggers multiple tasks by passing task instances, useful for static task sets.
```ts
export const parentTask = task({
id: "parent-task",
run: async (payload: string) => {
const results = await batch.triggerByTask([
{ task: childTask1, payload: { foo: "World" } },
{ task: childTask2, payload: { bar: 42 } },
]);
const run1 = await runs.retrieve(results.runs[0]);
const run2 = await runs.retrieve(results.runs[1]);
},
});
```
### batch.triggerByTaskAndWait()
Batch triggers multiple tasks by passing task instances and waits for all results.
```ts
export const parentTask = task({
id: "parent-task",
run: async (payload: string) => {
const { runs } = await batch.triggerByTaskAndWait([
{ task: childTask1, payload: { foo: "World" } },
{ task: childTask2, payload: { bar: 42 } },
]);
if (runs[0].ok) {
console.log("Child task 1 output", runs[0].output);
}
if (runs[1].ok) {
console.log("Child task 2 output", runs[1].output);
}
},
});
```
## Correct Metadata implementation
### Overview
Metadata allows attaching up to 256KB of structured data to a run, which can be accessed during execution, via API, Realtime, and in the dashboard. Useful for storing user information, tracking progress, or saving intermediate results.
### Basic Usage
Add metadata when triggering a task:
```ts
const handle = await myTask.trigger(
{ message: "hello world" },
{ metadata: { user: { name: "Eric", id: "user_1234" } } }
);
```
Access metadata inside a run:
```ts
import { task, metadata } from "@trigger.dev/sdk";
export const myTask = task({
id: "my-task",
run: async (payload: { message: string }) => {
// Get the whole metadata object
const currentMetadata = metadata.current();
// Get a specific key
const user = metadata.get("user");
console.log(user.name); // "Eric"
},
});
```
### Update methods
Metadata can be updated as the run progresses:
- **set**: `metadata.set("progress", 0.5)`
- **del**: `metadata.del("progress")`
- **replace**: `metadata.replace({ user: { name: "Eric" } })`
- **append**: `metadata.append("logs", "Step 1 complete")`
- **remove**: `metadata.remove("logs", "Step 1 complete")`
- **increment**: `metadata.increment("progress", 0.4)`
- **decrement**: `metadata.decrement("progress", 0.4)`
- **stream**: `await metadata.stream("logs", readableStream)`
- **flush**: `await metadata.flush()`
Updates can be chained with a fluent API:
```ts
metadata.set("progress", 0.1)
.append("logs", "Step 1 complete")
.increment("progress", 0.4);
```
### Parent & root updates
Child tasks can update parent task metadata:
```ts
export const childTask = task({
id: "child-task",
run: async (payload: { message: string }) => {
// Update parent task's metadata
metadata.parent.set("progress", 0.5);
// Update root task's metadata
metadata.root.set("status", "processing");
},
});
```
### Type safety
Metadata accepts any JSON-serializable object. For type safety, consider wrapping with Zod:
```ts
import { z } from "zod";
const Metadata = z.object({
user: z.object({
name: z.string(),
id: z.string(),
}),
date: z.coerce.date(),
});
function getMetadata() {
return Metadata.parse(metadata.current());
}
```
### Important notes
- Metadata methods only work inside run functions or task lifecycle hooks
- Metadata is NOT automatically propagated to child tasks
- Maximum size is 256KB (configurable if self-hosting)
- Objects like Dates are serialized to strings and must be deserialized when retrieved
## Correct Realtime implementation
### Overview
Trigger.dev Realtime enables subscribing to runs for real-time updates on run status, useful for monitoring tasks, updating UIs, and building realtime dashboards. It's built on Electric SQL, a PostgreSQL syncing engine.
### Basic usage
Subscribe to a run after triggering a task:
```ts
import { runs, tasks } from "@trigger.dev/sdk";
async function myBackend() {
const handle = await tasks.trigger("my-task", { some: "data" });
for await (const run of runs.subscribeToRun(handle.id)) {
console.log(run); // Logs the run every time it changes
}
}
```
### Subscription methods
- **subscribeToRun**: Subscribe to changes for a specific run
- **subscribeToRunsWithTag**: Subscribe to changes for all runs with a specific tag
- **subscribeToBatch**: Subscribe to changes for all runs in a batch
### Type safety
You can infer types of run's payload and output by passing the task type:
```ts
import { runs } from "@trigger.dev/sdk";
import type { myTask } from "./trigger/my-task";
for await (const run of runs.subscribeToRun<typeof myTask>(handle.id)) {
console.log(run.payload.some); // Type-safe access to payload
if (run.output) {
console.log(run.output.result); // Type-safe access to output
}
}
```
### Realtime Streams
Stream data in realtime from inside your tasks using the metadata system:
```ts
import { task, metadata } from "@trigger.dev/sdk";
import OpenAI from "openai";
export type STREAMS = {
openai: OpenAI.ChatCompletionChunk;
};
export const myTask = task({
id: "my-task",
run: async (payload: { prompt: string }) => {
const completion = await openai.chat.completions.create({
messages: [{ role: "user", content: payload.prompt }],
model: "gpt-3.5-turbo",
stream: true,
});
// Register the stream with the key "openai"
const stream = await metadata.stream("openai", completion);
let text = "";
for await (const chunk of stream) {
text += chunk.choices.map((choice) => choice.delta?.content).join("");
}
return { text };
},
});
```
Subscribe to streams using `withStreams`:
```ts
for await (const part of runs.subscribeToRun<typeof myTask>(runId).withStreams<STREAMS>()) {
switch (part.type) {
case "run": {
console.log("Received run", part.run);
break;
}
case "openai": {
console.log("Received OpenAI chunk", part.chunk);
break;
}
}
}
```
## Realtime hooks
### Installation
```bash
npm add @trigger.dev/react-hooks
```
### Authentication
All hooks require a Public Access Token. You can provide it directly to each hook:
```ts
import { useRealtimeRun } from "@trigger.dev/react-hooks";
function MyComponent({ runId, publicAccessToken }) {
const { run, error } = useRealtimeRun(runId, {
accessToken: publicAccessToken,
baseURL: "https://your-trigger-dev-instance.com", // Optional for self-hosting
});
}
```
Or use the `TriggerAuthContext` provider:
```ts
import { TriggerAuthContext } from "@trigger.dev/react-hooks";
function SetupTrigger({ publicAccessToken }) {
return (
<TriggerAuthContext.Provider value={{ accessToken: publicAccessToken }}>
<MyComponent />
</TriggerAuthContext.Provider>
);
}
```
For Next.js App Router, wrap the provider in a client component:
```ts
// components/TriggerProvider.tsx
"use client";
import { TriggerAuthContext } from "@trigger.dev/react-hooks";
export function TriggerProvider({ accessToken, children }) {
return (
<TriggerAuthContext.Provider value={{ accessToken }}>
{children}
</TriggerAuthContext.Provider>
);
}
```
### Passing tokens to the frontend
Several approaches for Next.js App Router:
1. **Using cookies**:
```ts
// Server action
export async function startRun() {
const handle = await tasks.trigger<typeof exampleTask>("example", { foo: "bar" });
cookies().set("publicAccessToken", handle.publicAccessToken);
redirect(`/runs/${handle.id}`);
}
// Page component
export default function RunPage({ params }) {
const publicAccessToken = cookies().get("publicAccessToken");
return (
<TriggerProvider accessToken={publicAccessToken}>
<RunDetails id={params.id} />
</TriggerProvider>
);
}
```
2. **Using query parameters**:
```ts
// Server action
export async function startRun() {
const handle = await tasks.trigger<typeof exampleTask>("example", { foo: "bar" });
redirect(`/runs/${handle.id}?publicAccessToken=${handle.publicAccessToken}`);
}
```
3. **Server-side token generation**:
```ts
// Page component
export default async function RunPage({ params }) {
const publicAccessToken = await generatePublicAccessToken(params.id);
return (
<TriggerProvider accessToken={publicAccessToken}>
<RunDetails id={params.id} />
</TriggerProvider>
);
}
// Token generation function
export async function generatePublicAccessToken(runId: string) {
return auth.createPublicToken({
scopes: {
read: {
runs: [runId],
},
},
expirationTime: "1h",
});
}
```
### Hook types
#### SWR hooks
Data fetching hooks that use SWR for caching:
```ts
"use client";
import { useRun } from "@trigger.dev/react-hooks";
import type { myTask } from "@/trigger/myTask";
function MyComponent({ runId }) {
const { run, error, isLoading } = useRun<typeof myTask>(runId);
if (isLoading) return <div>Loading...</div>;
if (error) return <div>Error: {error.message}</div>;
return <div>Run: {run.id}</div>;
}
```
Common options:
- `revalidateOnFocus`: Revalidate when window regains focus
- `revalidateOnReconnect`: Revalidate when network reconnects
- `refreshInterval`: Polling interval in milliseconds
#### Realtime hooks
Hooks that use Trigger.dev's realtime API for live updates (recommended over polling).
For most use cases, Realtime hooks are preferred over SWR hooks with polling due to better performance and lower API usage.
### Authentication
For client-side usage, generate a public access token with appropriate scopes:
```ts
import { auth } from "@trigger.dev/sdk";
const publicToken = await auth.createPublicToken({
scopes: {
read: {
runs: ["run_1234"],
},
},
});
```
## Correct Idempotency implementation
Idempotency ensures that an operation produces the same result when called multiple times. Trigger.dev supports idempotency at the task level through the `idempotencyKey` option.
### Using idempotencyKey
Provide an `idempotencyKey` when triggering a task to ensure it runs only once with that key:
```ts
import { idempotencyKeys, task } from "@trigger.dev/sdk";
export const myTask = task({
id: "my-task",
retry: {
maxAttempts: 4,
},
run: async (payload: any) => {
// Create a key unique to this task run
const idempotencyKey = await idempotencyKeys.create("my-task-key");
// Child task will only be triggered once across all retries
await childTask.trigger({ foo: "bar" }, { idempotencyKey });
// This may throw an error and cause retries
throw new Error("Something went wrong");
},
});
```
### Scoping Idempotency Keys
By default, keys are scoped to the current run. You can create globally unique keys:
```ts
const idempotencyKey = await idempotencyKeys.create("my-task-key", { scope: "global" });
```
When triggering from backend code:
```ts