# Trigger > ## Documentation Index --- # Source: https://trigger.dev/docs/management/schedules/activate.md > ## Documentation Index > Fetch the complete documentation index at: https://trigger.dev/docs/llms.txt > Use this file to discover all available pages before exploring further. # Activate Schedule > Activate a schedule by its ID. This will only work on `IMPERATIVE` schedules that were created in the dashboard or using the imperative SDK functions like `schedules.create()`. ## OpenAPI ````yaml v3-openapi POST /api/v1/schedules/{schedule_id}/activate openapi: 3.1.0 info: title: Trigger.dev v3 REST API description: >- The REST API lets you trigger and manage runs on Trigger.dev. You can trigger a run, get the status of a run, and get the results of a run. version: 2024-04 license: name: Apache 2.0 url: https://www.apache.org/licenses/LICENSE-2.0.html servers: - url: https://api.trigger.dev description: Trigger.dev API security: [] paths: /api/v1/schedules/{schedule_id}/activate: post: tags: - schedules summary: Activate Schedule description: >- Activate a schedule by its ID. This will only work on `IMPERATIVE` schedules that were created in the dashboard or using the imperative SDK functions like `schedules.create()`. operationId: activate_schedule_v1 parameters: - in: path name: schedule_id required: true schema: type: string description: The ID of the schedule. responses: '200': description: Schedule updated successfully content: application/json: schema: $ref: '#/components/schemas/ScheduleObject' '401': description: Unauthorized request '404': description: Resource not found security: - secretKey: [] components: schemas: ScheduleObject: type: object properties: id: type: string example: sched_1234 description: The unique ID of the schedule, prefixed with 'sched_' task: type: string example: my-scheduled-task description: The id of the scheduled task that will be triggered by this schedule type: type: string example: IMPERATIVE description: >- The type of schedule, `DECLARATIVE` or `IMPERATIVE`. Declarative schedules are declared in your code by setting the `cron` property on a `schedules.task`. Imperative schedules are created in the dashboard or by using the imperative SDK functions like `schedules.create()`. active: type: boolean example: true description: Whether the schedule is active or not deduplicationKey: type: string description: The deduplication key used to prevent creating duplicate schedules example: dedup_key_1234 externalId: type: string description: >- The external ID of the schedule. Can be anything that is useful to you (e.g., user ID, org ID, etc.) example: user_1234 generator: type: object properties: type: type: string enum: - CRON expression: type: string description: The cron expression used to generate the schedule example: 0 0 * * * description: type: string description: The description of the generator in plain english example: Every day at midnight timezone: type: string example: America/New_York description: >- Defaults to UTC. In IANA format, if set then it will trigger at the CRON frequency in that timezone and respect daylight savings time. nextRun: type: string format: date-time description: The next time the schedule will run example: '2024-04-01T00:00:00Z' environments: type: array items: $ref: '#/components/schemas/ScheduleEnvironment' ScheduleEnvironment: type: object properties: id: type: string type: type: string userName: type: string securitySchemes: secretKey: type: http scheme: bearer description: > Use your project-specific Secret API key. Will start with `tr_dev_`, `tr_prod`, `tr_stg`, etc. You can find your Secret API key in the API Keys section of your Trigger.dev project dashboard. Our TypeScript SDK will default to using the value of the `TRIGGER_SECRET_KEY` environment variable if it is set. If you are using the SDK in a different environment, you can set the key using the `configure` function. ```typescript import { configure } from "@trigger.dev/sdk"; configure({ accessToken: "tr_dev_1234" }); ``` ```` --- # Source: https://trigger.dev/docs/config/extensions/additionalFiles.md > ## Documentation Index > Fetch the complete documentation index at: https://trigger.dev/docs/llms.txt > Use this file to discover all available pages before exploring further. # Additional Files > Use the additionalFiles build extension to copy additional files to the build directory Import the `additionalFiles` build extension and use it in your `trigger.config.ts` file: ```ts theme={"theme":"css-variables"} import { defineConfig } from "@trigger.dev/sdk"; import { additionalFiles } from "@trigger.dev/build/extensions/core"; export default defineConfig({ project: "", // Your other config settings... // We strongly recommend setting this to false // When set to `false`, the current working directory will be set to the build directory, which more closely matches production behavior. legacyDevProcessCwdBehaviour: false, // Default: true build: { extensions: [additionalFiles({ files: ["./assets/**", "wrangler/wrangler.toml"] })], }, }); ``` This will copy the files specified in the `files` array to the build directory. The `files` array can contain globs. The output paths will match the path of the file, relative to the root of the project. This extension effects both the `dev` and the `deploy` commands, and the resulting paths will be the same for both. If you use `legacyDevProcessCwdBehaviour: false`, you can then do this: ```ts theme={"theme":"css-variables"} import path from "node:path"; // You can use `process.cwd()` if you use `legacyDevProcessCwdBehaviour: false` const interRegularFont = path.join(process.cwd(), "assets/Inter-Regular.ttf"); ``` The root of the project is the directory that contains the trigger.config.ts file --- # Source: https://trigger.dev/docs/config/extensions/additionalPackages.md > ## Documentation Index > Fetch the complete documentation index at: https://trigger.dev/docs/llms.txt > Use this file to discover all available pages before exploring further. # Additional Packages > Use the additionalPackages build extension to include additional packages in the build Import the `additionalPackages` build extension and use it in your `trigger.config.ts` file: ```ts theme={"theme":"css-variables"} import { defineConfig } from "@trigger.dev/sdk"; import { additionalPackages } from "@trigger.dev/build/extensions/core"; export default defineConfig({ project: "", // Your other config settings... build: { extensions: [additionalPackages({ packages: ["wrangler"] })], }, }); ``` This allows you to include additional packages in the build that are not automatically included via imports. This is useful if you want to install a package that includes a CLI tool that you want to invoke in your tasks via `exec`. We will try to automatically resolve the version of the package but you can specify the version by using the `@` symbol: ```ts theme={"theme":"css-variables"} import { defineConfig } from "@trigger.dev/sdk"; export default defineConfig({ project: "", // Your other config settings... build: { extensions: [additionalPackages({ packages: ["wrangler@1.19.0"] })], }, }); ``` This extension does not do anything in `dev` mode, but it will install the packages in the build directory when you run `deploy`. The packages will be installed in the `node_modules` directory in the build directory. --- # Source: https://trigger.dev/docs/management/advanced-usage.md > ## Documentation Index > Fetch the complete documentation index at: https://trigger.dev/docs/llms.txt > Use this file to discover all available pages before exploring further. # Advanced usage > Advanced usage of the Trigger.dev management API ### Accessing raw HTTP responses All API methods return a `Promise` subclass `ApiPromise` that includes helpers for accessing the underlying HTTP response: ```ts theme={"theme":"css-variables"} import { runs } from "@trigger.dev/sdk"; async function main() { const { data: run, response: raw } = await runs.retrieve("run_1234").withResponse(); console.log(raw.status); console.log(raw.headers); const response = await runs.retrieve("run_1234").asResponse(); // Returns a Response object console.log(response.status); console.log(response.headers); } ``` --- # Source: https://trigger.dev/docs/guides/example-projects/anchor-browser-web-scraper.md > ## Documentation Index > Fetch the complete documentation index at: https://trigger.dev/docs/llms.txt > Use this file to discover all available pages before exploring further. # Automated website monitoring with Anchor Browser > Automated web monitoring using Trigger.dev's task scheduling and Anchor Browser's AI-powered browser automation. **WEB SCRAPING:** When web scraping, you MUST use a proxy to comply with our terms of service. Direct scraping of third-party websites without the site owner's permission using Trigger.dev Cloud is prohibited and will result in account suspension. See [this example](/guides/examples/puppeteer#scrape-content-from-a-web-page) which uses a proxy. ## Overview This example demonstrates automated web monitoring using Trigger.dev's task scheduling and Anchor Browser's AI-powered browser automation tools. The task runs daily at 5pm ET to find the cheapest Broadway tickets available for same-day shows. **How it works:** * Trigger.dev schedules and executes the monitoring task * Anchor Browser spins up a remote browser session with an AI agent * The AI agent uses computer vision and natural language processing to analyze the TDF website * AI agent returns the lowest-priced show with specific details: name, price, and showtime ## Tech stack * **[Node.js](https://nodejs.org)** runtime environment (version 18.2 or higher) * **[Trigger.dev](https://trigger.dev)** for task scheduling and task orchestration * **[Anchor Browser](https://anchorbrowser.io/)** for AI-powered browser automation * **[Playwright](https://playwright.dev/)** for browser automation libraries (handled via external dependencies) ## GitHub repo Click here to view the full code for this project in our examples repository on GitHub. You can fork it and use it as a starting point for your own project. ## Relevant code ### Broadway ticket monitor task This task runs daily at 5pm ET, in [src/trigger/broadway-monitor.ts](https://github.com/triggerdotdev/examples/tree/main/anchor-browser-web-scraper/src/trigger/broadway-monitor.ts): ```ts theme={"theme":"css-variables"} import { schedules } from "@trigger.dev/sdk"; import Anchorbrowser from "anchorbrowser"; export const broadwayMonitor = schedules.task({ id: "broadway-ticket-monitor", cron: "0 21 * * *", run: async (payload, { ctx }) => { const client = new Anchorbrowser({ apiKey: process.env.ANCHOR_BROWSER_API_KEY!, }); let session; try { // Create explicit session to get live view URL session = await client.sessions.create(); console.log(`Session ID: ${session.data.id}`); console.log(`Live View URL: https://live.anchorbrowser.io?sessionId=${session.data.id}`); const response = await client.tools.performWebTask({ sessionId: session.data.id, url: "https://www.tdf.org/discount-ticket-programs/tkts-by-tdf/tkts-live/", prompt: `Look for the "Broadway Shows" section on this page. Find the show with the absolute lowest starting price available right now and return the show name, current lowest price, and show time. Be very specific about the current price you see. Format as: Show: [name], Price: [exact current price], Time: [time]`, }); console.log("Raw response:", response); const result = response.data.result?.result || response.data.result || response.data; if (result && typeof result === "string" && result.includes("Show:")) { console.log(`🎭 Best Broadway Deal Found!`); console.log(result); return { success: true, bestDeal: result, liveViewUrl: `https://live.anchorbrowser.io?sessionId=${session.data.id}`, }; } else { console.log("No Broadway deals found today"); return { success: true, message: "No deals found" }; } } finally { if (session?.data?.id) { try { await client.sessions.delete(session.data.id); } catch (cleanupError) { console.warn("Failed to cleanup session:", cleanupError); } } } }, }); ``` ### Build configuration Since Anchor Browser uses browser automation libraries (Playwright) under the hood, we need to configure Trigger.dev to handle these dependencies properly by excluding them from the build bundle in [trigger.config.ts](https://github.com/triggerdotdev/examples/tree/main/anchor-browser-web-scraper/trigger.config.ts): ```ts theme={"theme":"css-variables"} import { defineConfig } from "@trigger.dev/sdk"; export default defineConfig({ project: "proj_your_project_id_here", // Get from Trigger.dev dashboard maxDuration: 3600, // 1 hour - plenty of time for web automation dirs: ["./src/trigger"], build: { external: ["playwright-core", "playwright", "chromium-bidi"], }, }); ``` ## Learn more * View the [Anchor Browser docs](https://anchorbrowser.io/docs) to learn more about Anchor Browser's AI-powered browser automation tools. * Check out the source code for the [Anchor Browser web scraper repo](https://github.com/triggerdotdev/examples/tree/main/anchor-browser-web-scraper) on GitHub. * Browser our [example projects](/guides/introduction) to see how you can use Trigger.dev with other services. --- # Source: https://trigger.dev/docs/apikeys.md > ## Documentation Index > Fetch the complete documentation index at: https://trigger.dev/docs/llms.txt > Use this file to discover all available pages before exploring further. # API keys > How to authenticate with Trigger.dev so you can trigger tasks. ### Authentication and your secret keys When you [trigger a task](/triggering) from your backend code, you need to set the `TRIGGER_SECRET_KEY` environment variable. Each environment has its own secret key. You can find the value on the API keys page in the Trigger.dev dashboard: How to find your secret key For preview branches, you need to also set the `TRIGGER_PREVIEW_BRANCH` environment variable as well. You can find the value on the API keys page when you're on the preview branch. ### Automatically Configuring the SDK To automatically configure the SDK with your secret key, you can set the `TRIGGER_SECRET_KEY` environment variable. The SDK will automatically use this value when calling API methods (like `trigger`). ```bash .env theme={"theme":"css-variables"} TRIGGER_SECRET_KEY="tr_dev_…" TRIGGER_PREVIEW_BRANCH="my-branch" # Only needed for preview branches ``` You can do the same if you are self-hosting and need to change the default URL by using `TRIGGER_API_URL`. ```bash .env theme={"theme":"css-variables"} TRIGGER_API_URL="https://trigger.example.com" TRIGGER_PREVIEW_BRANCH="my-branch" # Only needed for preview branches ``` The default URL is `https://api.trigger.dev`. ### Manually Configuring the SDK If you prefer to manually configure the SDK, you can call the `configure` method: ```ts theme={"theme":"css-variables"} import { configure } from "@trigger.dev/sdk"; import { myTask } from "./trigger/myTasks"; configure({ secretKey: "tr_dev_1234", // WARNING: Never actually hardcode your secret key like this previewBranch: "my-branch", // Only needed for preview branches baseURL: "https://mytrigger.example.com", // Optional }); async function triggerTask() { await myTask.trigger({ userId: "1234" }); // This will use the secret key and base URL you configured } ``` --- # Source: https://trigger.dev/docs/config/extensions/aptGet.md > ## Documentation Index > Fetch the complete documentation index at: https://trigger.dev/docs/llms.txt > Use this file to discover all available pages before exploring further. # apt-get > Use the aptGet build extension to install system packages into the deployed image You can install system packages into the deployed image using the `aptGet` extension: ```ts theme={"theme":"css-variables"} import { defineConfig } from "@trigger.dev/sdk"; import { aptGet } from "@trigger.dev/build/extensions/core"; export default defineConfig({ project: "", // Your other config settings... build: { extensions: [aptGet({ packages: ["ffmpeg"] })], }, }); ``` If you want to install a specific version of a package, you can specify the version like this: ```ts theme={"theme":"css-variables"} import { defineConfig } from "@trigger.dev/sdk"; export default defineConfig({ project: "", // Your other config settings... build: { extensions: [aptGet({ packages: ["ffmpeg=6.0-4"] })], }, }); ``` --- # Source: https://trigger.dev/docs/deployment/atomic-deployment.md > ## Documentation Index > Fetch the complete documentation index at: https://trigger.dev/docs/llms.txt > Use this file to discover all available pages before exploring further. # Atomic deploys > Use atomic deploys to coordinate changes to your tasks and your application. Atomic deploys in Trigger.dev allow you to synchronize the deployment of your application with a specific version of your tasks. This ensures that your application always uses the correct version of its associated tasks, preventing inconsistencies or errors due to version mismatches. ## How it works Atomic deploys achieve synchronization by deploying your tasks to Trigger.dev without promoting them to the default version. Instead, you explicitly specify the deployed task version in your application’s environment. Here’s the process at a glance: 1. **Deploy Tasks to Trigger.dev**: Use the Trigger.dev CLI to deploy your tasks with the `--skip-promotion` flag. This creates a new task version without making it the default. 2. **Capture the Deployment Version**: The CLI outputs the version of the deployed tasks, which you’ll use in the next step. 3. **Deploy Your Application**: Deploy your application (e.g., to Vercel), setting an environment variable like `TRIGGER_VERSION` to the captured task version. ## Vercel CLI & GitHub Actions If you deploy to Vercel via their CLI, you can use this sample workflow that demonstrates performing atomic deploys with GitHub Actions, Trigger.dev, and Vercel: ```yml theme={"theme":"css-variables"} name: Deploy to Trigger.dev (prod) on: push: branches: - main concurrency: group: ${{ github.workflow }} cancel-in-progress: true jobs: deploy: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - name: Use Node.js 20.x uses: actions/setup-node@v4 with: node-version: "20.x" - name: Install dependencies run: npm install - name: Deploy Trigger.dev id: deploy-trigger env: TRIGGER_ACCESS_TOKEN: ${{ secrets.TRIGGER_ACCESS_TOKEN }} run: | npx trigger.dev@latest deploy --skip-promotion - name: Deploy to Vercel run: npx vercel --yes --prod -e TRIGGER_VERSION=$TRIGGER_VERSION --token $VERCEL_TOKEN env: VERCEL_TOKEN: ${{ secrets.VERCEL_TOKEN }} TRIGGER_VERSION: ${{ steps.deploy-trigger.outputs.deploymentVersion }} - name: Promote Trigger.dev Version run: npx trigger.dev@latest promote $TRIGGER_VERSION env: TRIGGER_ACCESS_TOKEN: ${{ secrets.TRIGGER_ACCESS_TOKEN }} TRIGGER_VERSION: ${{ steps.deploy-trigger.outputs.deploymentVersion }} ``` * Deploy to Trigger.dev * The `npx trigger.dev deploy` command uses `--skip-promotion` to deploy the tasks without setting the version as the default. * The step’s id: `deploy-trigger` allows us to capture the deployment version in the output (deploymentVersion). * Deploy to Vercel: * The `npx vercel` command deploys the application, setting the `TRIGGER_VERSION` environment variable to the task version from the previous step. * The --prod flag ensures a production deployment, and -e passes the environment variable. * The `@trigger.dev/sdk` automatically uses the `TRIGGER_VERSION` environment variable to trigger the correct version of the tasks. For this workflow to work, you need to set up the following secrets in your GitHub repository: * `TRIGGER_ACCESS_TOKEN`: Your Trigger.dev personal access token. View the instructions [here](/github-actions) to learn more. * `VERCEL_TOKEN`: Your Vercel personal access token. You can find this in your Vercel account settings. ## Vercel GitHub integration If you're are using Vercel, chances are you are using their GitHub integration and deploying your application directly from pushes to GitHub. This section covers how to achieve atomic deploys with Trigger.dev in this setup. ### Turn off automatic promotion By default, Vercel automatically promotes new deployments to production. To prevent this, you need to disable the auto-promotion feature in your Vercel project settings: 1. Go to your Production environment settings in Vercel at `https://vercel.com///settings/environments/production` 2. Disable the "Auto-assign Custom Production Domains" setting: Vercel project settings showing the auto-promotion setting 3. Hit the "Save" button to apply the changes. Now whenever you push to your main branch, Vercel will deploy your application to the production environment without promoting it, and you can control the promotion manually. ### Deploy with Trigger.dev Now we want to deploy that same commit to Trigger.dev, and then promote the Vercel deployment when that completes. Here's a sample GitHub Actions workflow that does this: ```yml theme={"theme":"css-variables"} name: Deploy to Trigger.dev (prod) on: push: branches: - main concurrency: group: ${{ github.workflow }} cancel-in-progress: true jobs: deploy: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - name: Use Node.js 20.x uses: actions/setup-node@v4 with: node-version: "20.x" - name: Install dependencies run: npm install - name: Wait for vercel deployment (push) id: wait-for-vercel uses: ludalex/vercel-wait@v1 with: project-id: ${{ secrets.VERCEL_PROJECT_ID }} team-id: ${{ secrets.VERCEL_SCOPE_NAME }} token: ${{ secrets.VERCEL_TOKEN }} sha: ${{ github.sha }} - name: πŸš€ Deploy Trigger.dev id: deploy-trigger env: TRIGGER_ACCESS_TOKEN: ${{ secrets.TRIGGER_ACCESS_TOKEN }} run: | npx trigger.dev@latest deploy - name: Promote Vercel deploy run: npx vercel promote $VERCEL_DEPLOYMENT_ID --yes --token $VERCEL_TOKEN --scope $VERCEL_SCOPE_NAME env: VERCEL_DEPLOYMENT_ID: ${{ steps.wait-for-vercel.outputs.deployment-id }} VERCEL_TOKEN: ${{ secrets.VERCEL_TOKEN }} VERCEL_SCOPE_NAME: ${{ secrets.VERCEL_SCOPE_NAME }} ``` This workflow does the following: 1. Waits for the Vercel deployment to complete using the `ludalex/vercel-wait` action. 2. Deploys the tasks to Trigger.dev using the `npx trigger.dev deploy` command. There's no need to use the `--skip-promotion` flag because we want to promote the deployment. 3. Promotes the Vercel deployment using the `npx vercel promote` command. For this workflow to work, you need to set up the following secrets in your GitHub repository: * `TRIGGER_ACCESS_TOKEN`: Your Trigger.dev personal access token. View the instructions [here](/github-actions) to learn more. * `VERCEL_TOKEN`: Your Vercel personal access token. You can find this in your Vercel account settings. * `VERCEL_PROJECT_ID`: Your Vercel project ID. You can find this in your Vercel project settings. * `VERCEL_SCOPE_NAME`: Your Vercel team slug. Checkout our [example repo](https://github.com/ericallam/vercel-atomic-deploys) to see this workflow in action. We are using the `ludalex/vercel-wait` action above as a fork of the [official tj-actions/vercel-wait](https://github.com/tj-actions/vercel-wait) action because there is a bug in the official action that exits early if the deployment isn't found in the first check and due to the fact that it supports treating skipped (cancelled) Vercel deployments as valid (on by default). I've opened a PR for this issue [here](https://github.com/tj-actions/vercel-wait/pull/106). --- # Source: https://trigger.dev/docs/config/extensions/audioWaveform.md > ## Documentation Index > Fetch the complete documentation index at: https://trigger.dev/docs/llms.txt > Use this file to discover all available pages before exploring further. # Audio Waveform > Use the audioWaveform build extension to add support for Audio Waveform in your project Previously, we installed [Audio Waveform](https://github.com/bbc/audiowaveform) in the build image. That's been moved to a build extension: ```ts theme={"theme":"css-variables"} import { defineConfig } from "@trigger.dev/sdk"; import { audioWaveform } from "@trigger.dev/build/extensions/audioWaveform"; export default defineConfig({ project: "", // Your other config settings... build: { extensions: [audioWaveform()], // uses verson 1.1.0 of audiowaveform by default }, }); ``` --- # Source: https://trigger.dev/docs/realtime/auth.md > ## Documentation Index > Fetch the complete documentation index at: https://trigger.dev/docs/llms.txt > Use this file to discover all available pages before exploring further. # Realtime authentication > Authenticating real-time API requests with Public Access Tokens or Trigger Tokens To use the Realtime API, you need to authenticate your requests with Public Access Tokens or Trigger Tokens. These tokens provide secure, scoped access to your runs and can be used in both frontend and backend applications. ## Token Types There are two types of tokens you can use with the Realtime API: * **[Public Access Tokens](#public-access-tokens-for-subscribing-to-runs)** - Used to read and subscribe to run data. Can be used in both the frontend and backend. * **[Trigger Tokens](#trigger-tokens-for-frontend-triggering-only)** - Used to trigger tasks from your frontend. These are more secure, single-use tokens that can only be used in the frontend. ## Public Access Tokens (for subscribing to runs) Use Public Access Tokens to subscribe to runs and receive real-time updates in your frontend or backend. ### Creating Public Access Tokens You can create a Public Access Token using the `auth.createPublicToken` function in your **backend** code: ```tsx theme={"theme":"css-variables"} // Somewhere in your backend code import { auth } from "@trigger.dev/sdk"; const publicToken = await auth.createPublicToken(); // πŸ‘ˆ this public access token has no permissions, so is pretty useless! ``` ### Scopes By default a Public Access Token has no permissions. You must specify the scopes you need when creating a Public Access Token: ```ts theme={"theme":"css-variables"} import { auth } from "@trigger.dev/sdk"; const publicToken = await auth.createPublicToken({ scopes: { read: { runs: true, // ❌ this token can read all runs, possibly useful for debugging/testing }, }, }); ``` This will allow the token to read all runs, which is probably not what you want. You can specify only certain runs by passing an array of run IDs: ```ts theme={"theme":"css-variables"} import { auth } from "@trigger.dev/sdk"; const publicToken = await auth.createPublicToken({ scopes: { read: { runs: ["run_1234", "run_5678"], // βœ… this token can read only these runs }, }, }); ``` You can scope the token to only read certain tasks: ```ts theme={"theme":"css-variables"} import { auth } from "@trigger.dev/sdk"; const publicToken = await auth.createPublicToken({ scopes: { read: { tasks: ["my-task-1", "my-task-2"], // πŸ‘ˆ this token can read all runs of these tasks }, }, }); ``` Or tags: ```ts theme={"theme":"css-variables"} import { auth } from "@trigger.dev/sdk"; const publicToken = await auth.createPublicToken({ scopes: { read: { tags: ["my-tag-1", "my-tag-2"], // πŸ‘ˆ this token can read all runs with these tags }, }, }); ``` Or a specific batch of runs: ```ts theme={"theme":"css-variables"} import { auth } from "@trigger.dev/sdk"; const publicToken = await auth.createPublicToken({ scopes: { read: { batch: "batch_1234", // πŸ‘ˆ this token can read all runs in this batch }, }, }); ``` You can also combine scopes. For example, to read runs with specific tags and for specific tasks: ```ts theme={"theme":"css-variables"} import { auth } from "@trigger.dev/sdk"; const publicToken = await auth.createPublicToken({ scopes: { read: { tasks: ["my-task-1", "my-task-2"], tags: ["my-tag-1", "my-tag-2"], }, }, }); ``` ### Expiration By default, Public Access Token's expire after 15 minutes. You can specify a different expiration time when creating a Public Access Token: ```ts theme={"theme":"css-variables"} import { auth } from "@trigger.dev/sdk"; const publicToken = await auth.createPublicToken({ expirationTime: "1hr", }); ``` * If `expirationTime` is a string, it will be treated as a time span * If `expirationTime` is a number, it will be treated as a Unix timestamp * If `expirationTime` is a `Date`, it will be treated as a date The format used for a time span is the same as the [jose package](https://github.com/panva/jose), which is a number followed by a unit. Valid units are: "sec", "secs", "second", "seconds", "s", "minute", "minutes", "min", "mins", "m", "hour", "hours", "hr", "hrs", "h", "day", "days", "d", "week", "weeks", "w", "year", "years", "yr", "yrs", and "y". It is not possible to specify months. 365.25 days is used as an alias for a year. If the string is suffixed with "ago", or prefixed with a "-", the resulting time span gets subtracted from the current unix timestamp. A "from now" suffix can also be used for readability when adding to the current unix timestamp. ### Auto-generated tokens When you [trigger tasks](/triggering) from your backend, the `handle` received includes a `publicAccessToken` field. This token can be used to authenticate real-time requests in your frontend application. By default, auto-generated tokens expire after 15 minutes and have a read scope for the specific run(s) that were triggered. You can customize the expiration by passing a `publicTokenOptions` object to the trigger function. See our [triggering documentation](/triggering) for detailed examples of how to trigger tasks and get auto-generated tokens. ### Subscribing to runs with Public Access Tokens Once you have a Public Access Token, you can use it to authenticate requests to the Realtime API in both backend and frontend applications. **Backend usage:** See our [backend documentation](/realtime/backend) for examples of what you can do with Realtime in your backend once you have authenticated with a token. **Frontend usage:** See our [React hooks documentation](/realtime/react-hooks) for examples of using tokens with frontend components. ## Trigger Tokens (for frontend triggering only) For triggering tasks from your frontend, you need special "trigger" tokens. These tokens can only be used once to trigger a task and are more secure than regular Public Access Tokens. ### Creating Trigger Tokens ```ts theme={"theme":"css-variables"} import { auth } from "@trigger.dev/sdk"; // Somewhere in your backend code const triggerToken = await auth.createTriggerPublicToken("my-task"); ``` ### Multiple tasks You can pass multiple tasks to create a token that can trigger multiple tasks: ```ts theme={"theme":"css-variables"} import { auth } from "@trigger.dev/sdk"; // Somewhere in your backend code const triggerToken = await auth.createTriggerPublicToken(["my-task-1", "my-task-2"]); ``` ### Multiple use You can also create tokens that can be used multiple times: ```ts theme={"theme":"css-variables"} import { auth } from "@trigger.dev/sdk"; // Somewhere in your backend code const triggerToken = await auth.createTriggerPublicToken("my-task", { multipleUse: true, // ❌ Use this with caution! }); ``` ### Expiration These tokens also expire, with the default expiration time being 15 minutes. You can specify a custom expiration time: ```ts theme={"theme":"css-variables"} import { auth } from "@trigger.dev/sdk"; // Somewhere in your backend code const triggerToken = await auth.createTriggerPublicToken("my-task", { expirationTime: "24hr", }); ``` ### Triggering tasks from the frontend with Trigger Tokens Check out our [React hooks documentation](/realtime/react-hooks) for examples of how to use Trigger Tokens in your frontend applications. --- # Source: https://trigger.dev/docs/management/authentication.md > ## Documentation Index > Fetch the complete documentation index at: https://trigger.dev/docs/llms.txt > Use this file to discover all available pages before exploring further. # Authentication > Authenticating with the Trigger.dev management API There are two methods of authenticating with the management API: using a secret key associated with a specific environment in a project (`secretKey`), or using a personal access token (`personalAccessToken`). Both methods should only be used in a backend server, as they provide full access to the project. There is a separate authentication strategy when making requests from your frontend application. See the [Realtime guide](/realtime/overview) for more information. This guide is for backend usage only. Certain API functions work with both authentication methods, but require different arguments depending on the method used. For example, the `runs.list` function can be called using either a `secretKey` or a `personalAccessToken`, but the `projectRef` argument is required when using a `personalAccessToken`: ```ts theme={"theme":"css-variables"} import { configure, runs } from "@trigger.dev/sdk"; // Using secretKey authentication configure({ secretKey: process.env["TRIGGER_SECRET_KEY"], // starts with tr_dev_ or tr_prod_ }); function secretKeyExample() { return runs.list({ limit: 10, status: ["COMPLETED"], }); } // Using personalAccessToken authentication configure({ secretKey: process.env["TRIGGER_ACCESS_TOKEN"], // starts with tr_pat_ }); function personalAccessTokenExample() { // Notice the projectRef argument is required when using a personalAccessToken return runs.list("prof_1234", { limit: 10, status: ["COMPLETED"], projectRef: "tr_proj_1234567890", }); } ``` Consult the following table to see which endpoints support each authentication method. | Endpoint | Secret key | Personal Access Token | | ---------------------- | ---------- | --------------------- | | `task.trigger` | βœ… | | | `task.batchTrigger` | βœ… | | | `runs.list` | βœ… | βœ… | | `runs.retrieve` | βœ… | | | `runs.cancel` | βœ… | | | `runs.replay` | βœ… | | | `envvars.list` | βœ… | βœ… | | `envvars.retrieve` | βœ… | βœ… | | `envvars.upload` | βœ… | βœ… | | `envvars.create` | βœ… | βœ… | | `envvars.update` | βœ… | βœ… | | `envvars.del` | βœ… | βœ… | | `schedules.list` | βœ… | | | `schedules.create` | βœ… | | | `schedules.retrieve` | βœ… | | | `schedules.update` | βœ… | | | `schedules.activate` | βœ… | | | `schedules.deactivate` | βœ… | | | `schedules.del` | βœ… | | ### Secret key Secret key authentication scopes the API access to a specific environment in a project, and works with certain endpoints. You can read our [API Keys guide](/apikeys) for more information. ### Personal Access Token (PAT) A PAT is a token associated with a specific user, and gives access to all the orgs, projects, and environments that the user has access to. You can identify a PAT by the `tr_pat_` prefix. Because a PAT does not scope access to a specific environment, you must provide the `projectRef` argument when using a PAT (and sometimes the environment as well). For example, when uploading environment variables using a PAT, you must provide the `projectRef` and `environment` arguments: ```ts theme={"theme":"css-variables"} import { configure, envvars } from "@trigger.dev/sdk"; configure({ secretKey: process.env["TRIGGER_ACCESS_TOKEN"], // starts with tr_pat_ }); await envvars.upload("proj_1234", "dev", { variables: { MY_ENV_VAR: "MY_ENV_VAR_VALUE", }, override: true, }); ``` ### Preview branch targeting When working with preview branches, you may need to target a specific branch when making API calls. This is particularly useful for managing environment variables or other resources that are scoped to individual preview branches. To target a specific preview branch, include the `previewBranch` option in your SDK configuration: ```ts theme={"theme":"css-variables"} import { configure, envvars } from "@trigger.dev/sdk"; configure({ secretKey: process.env["TRIGGER_ACCESS_TOKEN"], // starts with tr_pat_ previewBranch: "feature-xyz", }); await envvars.update("proj_1234", "preview", "DATABASE_URL", { value: "your_preview_database_url", }); ``` To target a specific preview branch, include the `x-trigger-branch` header in your API requests with the branch name as the value: ```bash theme={"theme":"css-variables"} curl --request PUT \ --url https://api.trigger.dev/api/v1/projects/{projectRef}/envvars/preview/DATABASE_URL \ --header 'Authorization: Bearer ' \ --header 'x-trigger-branch: feature-xyz' \ --header 'Content-Type: application/json' \ --data '{ "value": "your_preview_database_url" }' ``` This will set the `DATABASE_URL` environment variable specifically for the `feature-xyz` preview branch. The `x-trigger-branch` header is only relevant when working with the `preview` environment (`{env} ` parameter set to `preview`). It has no effect when working with `dev`, `staging`, or `prod` environments. #### SDK usage with preview branches When using the SDK to manage preview branch environment variables, the branch targeting is handled automatically when you're running in a preview environment with the `TRIGGER_PREVIEW_BRANCH` environment variable set. However, you can also specify the branch explicitly: ```ts theme={"theme":"css-variables"} import { configure, envvars } from "@trigger.dev/sdk"; configure({ secretKey: process.env["TRIGGER_ACCESS_TOKEN"], // starts with tr_pat_ previewBranch: "feature-xyz", // Optional: specify the branch }); await envvars.update("proj_1234", "preview", "DATABASE_URL", { value: "your_preview_database_url", }); ``` --- # Source: https://trigger.dev/docs/management/auto-pagination.md > ## Documentation Index > Fetch the complete documentation index at: https://trigger.dev/docs/llms.txt > Use this file to discover all available pages before exploring further. # Auto-pagination > Using auto-pagination with the Trigger.dev management API All list endpoints in the management API support auto-pagination. You can use `for await … of` syntax to iterate through items across all pages: ```ts theme={"theme":"css-variables"} import { runs } from "@trigger.dev/sdk"; async function fetchAllRuns() { const allRuns = []; for await (const run of runs.list({ limit: 10 })) { allRuns.push(run); } return allRuns; } ``` You can also use helpers on the return value from any `list` method to get the next/previous page of results: ```ts theme={"theme":"css-variables"} import { runs } from "@trigger.dev/sdk"; async function main() { let page = await runs.list({ limit: 10 }); for (const run of page.data) { console.log(run); } while (page.hasNextPage()) { page = await page.getNextPage(); // ... do something with the next page } } ``` --- # Source: https://trigger.dev/docs/guides/example-projects/batch-llm-evaluator.md > ## Documentation Index > Fetch the complete documentation index at: https://trigger.dev/docs/llms.txt > Use this file to discover all available pages before exploring further. # Next.js Batch LLM Evaluator > This example Next.js project evaluates multiple LLM models using the Vercel AI SDK and streams updates to the frontend using Trigger.dev Realtime. ## Overview This demo is a full stack example that uses the following: * A [Next.js](https://nextjs.org/) app with [Prisma](https://www.prisma.io/) for the database. * Trigger.dev [Realtime](https://trigger.dev/launchweek/0/realtime) to stream updates to the frontend. * Work with multiple LLM models using the Vercel [AI SDK](https://sdk.vercel.ai/docs/introduction). (OpenAI, Anthropic, XAI) * Distribute tasks across multiple tasks using the new [`batch.triggerByTaskAndWait`](https://trigger.dev/docs/triggering#batch-triggerbytaskandwait) method. ## GitHub repo Click here to view the full code for this project in our examples repository on GitHub. You can fork it and use it as a starting point for your own project. ## Video