---
title: "Triggering"
description: "Tasks need to be triggered to run."
---
There are currently six ways you can trigger tasks:
| Function | Where does this work? | What it does |
| -------------------------------- | --------------------- | ---------------------------------------------------------------------------------------------------------------------------------- |
| `yourTask.trigger()` | Anywhere | Triggers a task and gets a handle you can use to monitor and manage the run. It does not wait for the result. |
| `yourTask.batchTrigger()` | Anywhere | Triggers a task multiple times and gets a handle you can use to monitor and manage the runs. It does not wait for the results. |
| `yourTask.triggerAndWait()` | Inside a task | Triggers a task and then waits until it's complete. You get the result data to continue with. |
| `yourTask.batchTriggerAndWait()` | Inside a task | Triggers a task multiple times in parallel and then waits until they're all complete. You get the resulting data to continue with. |
| `tasks.trigger()` | Outside of a task | Triggers a task and gets a handle you can use to fetch and manage the run. |
| `tasks.batchTrigger()` | Outside of a task | Triggers a task multiple times and gets a handle you can use to fetch and manage the runs. |
Additionally, [scheduled tasks](/v3/tasks-scheduled) get automatically triggered on their schedule and [webhooks](/v3/tasks-webhooks) when receiving a webhook.
## Scheduled tasks
You should attach one or more schedules to your `schedules.task()` to trigger it on a recurring schedule. [Read the scheduled tasks docs](/v3/tasks-scheduled).
## Authentication
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. [More info on API keys](/v3/apikeys).
## Task instance methods
Task instance methods are available on the `Task` object you receive when you define a task. They can be called from your backend code or from inside another task.
### Task.trigger()
Triggers a single run of a task with the payload you pass in, and any options you specify. It does NOT wait for the result, you cannot do that from outside a task.
If called from within a task, you can use the `AndWait` version to pause execution until the triggered run is complete.
```ts Next.js API route
import { emailSequence } from "~/trigger/emails";
//app/email/route.ts
export async function POST(request: Request) {
//get the JSON from the request
const data = await request.json();
//trigger your task
const handle = await emailSequence.trigger({ to: data.email, name: data.name });
//return a success response with the handle
return Response.json(handle);
}
```
```ts Remix
import { emailSequence } from "~/trigger/emails";
export async function action({ request, params }: ActionFunctionArgs) {
if (request.method.toUpperCase() !== "POST") {
return json("Method Not Allowed", { status: 405 });
}
//get the JSON from the request
const data = await request.json();
//trigger your task
const handle = await emailSequence.trigger({ to: data.email, name: data.name });
//return a success response with the handle
return json(handle);
}
```
```ts /trigger/my-task.ts
import { myOtherTask } from "~/trigger/my-other-task";
export const myTask = task({
id: "my-task",
run: async (payload: string) => {
const handle = await myOtherTask.trigger("some data");
//...do other stuff
},
});
```
### Task.batchTrigger()
Triggers multiples runs of a task with the payloads you pass in, and any options you specify.
```ts Next.js API route
import { emailSequence } from "~/trigger/emails";
//app/email/route.ts
export async function POST(request: Request) {
//get the JSON from the request
const data = await request.json();
//batch trigger your task
const batchHandle = await emailSequence.batchTrigger(
data.users.map((u) => ({ payload: { to: u.email, name: u.name } }))
);
//return a success response with the handle
return Response.json(batchHandle);
}
```
```ts Remix
import { emailSequence } from "~/trigger/emails";
export async function action({ request, params }: ActionFunctionArgs) {
if (request.method.toUpperCase() !== "POST") {
return json("Method Not Allowed", { status: 405 });
}
//get the JSON from the request
const data = await request.json();
//batch trigger your task
const batchHandle = await emailSequence.batchTrigger(
data.users.map((u) => ({ payload: { to: u.email, name: u.name } }))
);
//return a success response with the handle
return json(batchHandle);
}
```
```ts /trigger/my-task.ts
import { myOtherTask } 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
},
});
```
### Task.triggerAndWait()
This is where it gets interesting. You can trigger a task and then wait for the result. This is useful when you need to call a different task and then use the result to continue with your task.
Instead, use `batchTriggerAndWait()` if you can, or a for loop if you can't.
To control concurrency using batch triggers, you can set `queue.concurrencyLimit` on the child task.
```ts /trigger/batch.ts
export const batchTask = task({
id: "batch-task",
run: async (payload: string) => {
const results = await childTask.batchTriggerAndWait([
{ payload: "item1" },
{ payload: "item2" },
]);
console.log("Results", results);
//...do stuff with the results
},
});
```
```ts /trigger/loop.ts
export const loopTask = task({
id: "loop-task",
run: async (payload: string) => {
//this will be slower than the batch version
//as we have to resume the parent after each iteration
for (let i = 0; i < 2; i++) {
const result = await childTask.triggerAndWait(`item${i}`);
console.log("Result", result);
//...do stuff with the result
}
},
});
```
```ts /trigger/parent.ts
export const parentTask = task({
id: "parent-task",
run: async (payload: string) => {
const result = await batchChildTask.triggerAndWait("some-data");
console.log("Result", result);
//...do stuff with the result
},
});
```
### Task.batchTriggerAndWait()
You can batch trigger a task and wait for all the results. This is useful for the fan-out pattern, where you need to call a task multiple times and then wait for all the results to continue with your task.
Instead, pass in all items at once and set an appropriate `maxConcurrency`. Alternatively, use sequentially with a for loop.
To control concurrency, you can set `queue.concurrencyLimit` on the child task.
```ts /trigger/batch.ts
export const batchTask = task({
id: "batch-task",
run: async (payload: string) => {
const results = await childTask.batchTriggerAndWait([
{ payload: "item1" },
{ payload: "item2" },
]);
console.log("Results", results);
//...do stuff with the results
},
});
```
```ts /trigger/loop.ts
export const loopTask = task({
id: "loop-task",
run: async (payload: string) => {
//this will be slower than a single batchTriggerAndWait()
//as we have to resume the parent after each iteration
for (let i = 0; i < 2; i++) {
const result = await childTask.batchTriggerAndWait([
{ payload: `itemA${i}` },
{ payload: `itemB${i}` },
]);
console.log("Result", result);
//...do stuff with the result
}
},
});
```
```ts /trigger/nested.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
},
});
```
## SDK functions
You can trigger any task from your backend code using the `tasks.trigger()` or `tasks.batchTrigger()` SDK functions.
Do not trigger tasks directly from your frontend. If you do, you will leak your private
Trigger.dev API key.
You can use Next.js Server Actions but [you need to be careful with bundling](#next-js-server-actions).
### tasks.trigger()
Triggers a single run of a task with the payload you pass in, and any options you specify, without needing to import the task.
Why would you use this instead of the `Task.trigger()` instance method? Tasks can import
dependencies/modules that you might not want included in your application code or cause problems
with building.
```ts Next.js API route
import { tasks } from "@trigger.dev/sdk/v3";
import type { emailSequence } from "~/trigger/emails";
// 👆 **type-only** import
//app/email/route.ts
export async function POST(request: Request) {
//get the JSON from the request
const data = await request.json();
// Pass the task type to `trigger()` as a generic argument, giving you full type checking
const handle = await tasks.trigger("email-sequence", {
to: data.email,
name: data.name,
});
//return a success response with the handle
return Response.json(handle);
}
```
```ts Remix
import { tasks } from "@trigger.dev/sdk/v3";
export async function action({ request, params }: ActionFunctionArgs) {
if (request.method.toUpperCase() !== "POST") {
return json("Method Not Allowed", { status: 405 });
}
//get the JSON from the request
const data = await request.json();
// The generic argument is optional, but recommended for full type checking
const handle = await tasks.trigger("email-sequence", {
to: data.email,
name: data.name,
});
//return a success response with the handle
return json(handle);
}
```
By importing the task with the type modifier, the import of `"~/trigger/emails"` is a type-only
import. This means that the task code is not included in your application at build time.
### tasks.batchTrigger()
Triggers multiples runs of a task with the payloads you pass in, and any options you specify, without needing to import the task.
```ts Next.js API route
import { tasks } from "@trigger.dev/sdk/v3";
import type { emailSequence } from "~/trigger/emails";
// 👆 **type-only** import
//app/email/route.ts
export async function POST(request: Request) {
//get the JSON from the request
const data = await request.json();
// Pass the task type to `batchTrigger()` as a generic argument, giving you full type checking
const batchHandle = await tasks.batchTrigger(
"email-sequence",
data.users.map((u) => ({ payload: { to: u.email, name: u.name } }))
);
//return a success response with the handle
return Response.json(batchHandle);
}
```
### tasks.triggerAndPoll()
Triggers a single run of a task with the payload you pass in, and any options you specify, and then polls the run until it's complete.
```ts Next.js API route
import { tasks } from "@trigger.dev/sdk/v3";
import type { emailSequence } from "~/trigger/emails";
//app/email/route.ts
export async function POST(request: Request) {
//get the JSON from the request
const data = await request.json();
// Pass the task type to `triggerAndPoll()` as a generic argument, giving you full type checking
const result = await tasks.triggerAndPoll(
"email-sequence",
{
to: data.email,
name: data.name,
},
{ pollIntervalMs: 5000 }
);
//return a success response with the result
return Response.json(result);
}
```
The above code is just a demonstration of the API and is not recommended to use in an API route
this way as it will block the request until the task is complete.
### runs.retrieve()
You can retrieve a run by its handle using the `runs.retrieve()` function.
```ts Next.js API route
import { tasks, runs } from "@trigger.dev/sdk/v3";
import type { emailSequence } from "~/trigger/emails";
// 👆 **type-only** import
//app/email/route.ts
export async function POST(request: Request) {
//get the JSON from the request
const data = await request.json();
// Pass the task type to `trigger()` as a generic argument, giving you full type checking
const handle = await tasks.trigger("email-sequence", {
to: data.email,
name: data.name,
});
const run = await runs.retrieve(handle);
// run.output will be correctly typed as the return value of the task
return Response.json(run.output);
}
```
### runs.poll()
You can poll a run by its handle using the `runs.poll()` function.
```ts Next.js API route
import { tasks, runs } from "@trigger.dev/sdk/v3";
import type { emailSequence } from "~/trigger/emails";
// 👆 **type-only** import
//app/email/route.ts
export async function POST(request: Request) {
//get the JSON from the request
const data = await request.json();
// Pass the task type to `trigger()` as a generic argument, giving you full type checking
const handle = await tasks.trigger("email-sequence", {
to: data.email,
name: data.name,
});
// Poll the run until it's complete
const run = await runs.poll(handle, { pollIntervalMs: 5000 });
// run.output will be correctly typed as the return value of the task
return Response.json(run.output);
}
```
## Next.js Server Actions
Server Actions allow you to call your backend code without creating API routes. This is very useful for triggering tasks but you need to be careful you don't accidentally bundle the Trigger.dev SDK into your frontend code.
If you see an error like this then you've bundled `@trigger.dev/sdk/v3` into your frontend code:
```bash
Module build failed: UnhandledSchemeError: Reading from "node:crypto" is not handled by plugins (Unhandled scheme).
Module build failed: UnhandledSchemeError: Reading from "node:process" is not handled by plugins (Unhandled scheme).
Webpack supports "data:" and "file:" URIs by default.
You may need an additional plugin to handle "node:" URIs.
```
When you use server actions that use `@trigger.dev/sdk/v3`:
- The file can't have any React components in it.
- The file should have `"use server"` on the first line.
Here's an example of how to do it with a component that calls the server action and the actions file:
```tsx app/page.tsx
"use client";
import { create } from "@/app/actions";
export default function Home() {
return (
);
}
```
```tsx app/actions.ts
"use server";
import { createAvatar } from "@/trigger/create-avatar";
export async function create() {
try {
const handle = await createAvatar.trigger({
userImage: "http://...",
});
return { handle };
} catch (error) {
console.error(error);
return {
error: "something went wrong",
};
}
}
```