Tasks are functions that can run for a long time and provide strong resilience to failure.
Tasks are the core primitive of Trigger.dev. They are async functions that run in the background, support retries, and can execute for as long as needed — no timeouts.There are different types of tasks:
Regular tasks — triggered manually from your backend or from another task.
Scheduled tasks — triggered on a recurring cron schedule. See Scheduled tasks.
import { task } from "@trigger.dev/sdk";export const helloWorld = task({ // Unique identifier for this task id: "hello-world", // The run function is called when the task is triggered run: async (payload: { message: string }) => { console.log(payload.message); },});
You can trigger this in two ways:
From the dashboard using the Test feature.
From your backend code using the SDK. See Triggering.
Here is how to trigger a single run from your backend:
Your backend code
import { helloWorld } from "./trigger/hello-world";async function triggerHelloWorld() { const handle = await helloWorld.trigger({ message: "Hello world!" }); console.log("Task is running with handle", handle.id);}
Task middleware runs at the top level, wrapping the entire task lifecycle including all hooks. Use the locals API to share data between middleware and hooks.
db.ts
import { locals, logger, tasks } from "@trigger.dev/sdk";const DbLocal = locals.create<{ connect: () => Promise<void>; disconnect: () => Promise<void> }>("db");export function getDb() { return locals.getOrThrow(DbLocal);}tasks.middleware("db", async ({ ctx, payload, next, task }) => { const db = locals.set(DbLocal, { connect: async () => logger.info("Connecting to the database"), disconnect: async () => logger.info("Disconnecting from the database"), }); await db.connect(); await next(); await db.disconnect();});// Disconnect when the run is pausedtasks.onWait("db", async ({ ctx, payload, task }) => { const db = getDb(); await db.disconnect();});// Reconnect when the run is resumedtasks.onResume("db", async ({ ctx, payload, task }) => { const db = getDb(); await db.connect();});
Access the database client in your tasks using getDb():