### Install Queuebase for Next.js Source: https://docs.queuebase.com/getting-started/introduction Install the Next.js SDK and a validation library like Zod. ```bash # Zod is shown here, but any Standard Schema-compatible library works npm install @queuebase/nextjs zod ``` -------------------------------- ### Start the development server Source: https://docs.queuebase.com/guides/dev-server Launches the local development server using the CLI. ```bash npx queuebase dev [options] ``` -------------------------------- ### Install Queuebase SDK and CLI Source: https://docs.queuebase.com/integrations/supastarter Install the necessary packages for Queuebase integration. pnpm is used here, but npm or yarn can also be used. ```bash pnpm add @queuebase/nextjs zod pnpm add -D @queuebase/cli ``` -------------------------------- ### Install Queuebase for Node.js Source: https://docs.queuebase.com/getting-started/introduction Install the Node.js SDK and a validation library like Zod for frameworks such as Express or Fastify. ```bash # Zod is shown here, but any Standard Schema-compatible library works npm install @queuebase/node zod ``` -------------------------------- ### Enqueue with options Source: https://docs.queuebase.com/guides/enqueueing-jobs Example demonstrating how to provide configuration options like delay, retries, and backoff strategy during enqueueing. ```javascript await jobClient.sendEmail.enqueue( { to: "user@example.com", subject: "Hi", body: "Hello" }, { delay: "5m", retries: 5, backoff: "exponential", backoffDelay: 2000, }, ); ``` -------------------------------- ### Install Queuebase dependencies Source: https://docs.queuebase.com/getting-started/nodejs Install the required Queuebase package and a validation library like Zod. ```bash npm install @queuebase/node zod ``` -------------------------------- ### Run development server and application Source: https://docs.queuebase.com/getting-started/nodejs Commands to start the Queuebase CLI dev server and the Node.js application. ```bash npx queuebase dev ``` ```bash node src/index.ts ``` -------------------------------- ### Start Application Server Source: https://docs.queuebase.com/integrations/supastarter Run your application server in a separate terminal. Ensure this is running for Queuebase to communicate with your app. ```bash pnpm dev ``` -------------------------------- ### Install Queuebase Next.js SDK Source: https://docs.queuebase.com/getting-started/nextjs Install the necessary packages for Queuebase integration with Next.js. Zod is used for schema validation, but other compatible libraries can be used. ```bash npm install @queuebase/nextjs zod ``` -------------------------------- ### Schedule formats Source: https://docs.queuebase.com/guides/scheduled-jobs Examples of supported schedule formats including plain English, raw cron, and configuration objects. ```text schedule: "every 5 minutes" schedule: "every hour" schedule: "every 2 hours" schedule: "every day at 9am" schedule: "every weekday at 9am" schedule: "every monday at 2pm" ``` ```text schedule: "*/5 * * * *" // every 5 minutes schedule: "0 9 * * *" // daily at 9am schedule: "0 9 * * 1-5" // weekdays at 9am ``` ```javascript schedule: { cron: "0 9 * * *", timezone: "America/New_York", enabled: true, overlap: "skip", } ``` -------------------------------- ### Start Queuebase Development Server Source: https://docs.queuebase.com/integrations/supastarter Run the Queuebase development server in a terminal. This server uses a local SQLite database and polls for jobs. ```bash npx queuebase dev ``` -------------------------------- ### Run Queuebase Dev Server Source: https://docs.queuebase.com/getting-started/nextjs Start the Queuebase development server in one terminal using `npx queuebase dev`. This server uses a local SQLite database and polls for jobs. ```bash npx queuebase dev ``` -------------------------------- ### Dry Run Output Example Source: https://docs.queuebase.com/reference/cli This output demonstrates the diff format shown when using the `--dry-run` flag with `queuebase sync`, indicating additions (+), updates (~), and deletions (-). ```text Dry run — no changes applied + dailyReport (0 9 * * *, UTC) ~ weeklyDigest cronExpression: "0 9 * * 1" → "0 10 * * 1" - oldCleanup (will be soft-deleted) 1 to insert, 1 to update, 1 to delete ``` -------------------------------- ### Run Next.js App Source: https://docs.queuebase.com/getting-started/nextjs Start your Next.js application in another terminal using `npm run dev`. Ensure both the Queuebase dev server and your Next.js app are running to test job execution. ```bash npm run dev ``` -------------------------------- ### Defining a Scheduled Job Source: https://docs.queuebase.com/guides/scheduled-jobs Example of defining a scheduled job with an empty input schema and a schedule property. ```APIDOC ## Defining a Scheduled Job Add a `schedule` property to any job with an empty input schema. ```javascript import { createJobRouter, job } from "@queuebase/nextjs"; import { z } from "zod"; export const jobs = createJobRouter({ dailyReport: job({ input: z.object({}), handler: async ({ jobId }) => { // runs every day at 9am UTC return { generated: true }; }, schedule: "every day at 9am", }), }); ``` **Note**: Only jobs with an empty input schema (e.g., `z.object({})` in Zod) can have a schedule. This is enforced by TypeScript — scheduled jobs run automatically with no user-provided input. ``` -------------------------------- ### Configure Router Path Source: https://docs.queuebase.com/reference/cli If no convention path matches for router discovery, the CLI looks for a config file. This example shows how to specify the router path in `queuebase.config.ts`. ```typescript export default { routerPath: "./src/jobs/index.ts", }; ``` -------------------------------- ### GET /status Source: https://docs.queuebase.com/guides/enqueueing-jobs Fetches the current status and result of a previously enqueued job. ```APIDOC ## GET /status ### Description Polls the current state of a job using the getStatus function returned during enqueueing. ### Response #### Success Response (200) - **publicId** (string) - Public job ID. - **name** (string) - Job name. - **status** ('pending' | 'running' | 'completed' | 'failed' | 'cancelled') - Current status. - **attempt** (number) - Current attempt number. - **maxAttempts** (number) - Maximum attempts allowed. - **createdAt** (string) - ISO timestamp. - **startedAt** (string | null) - ISO timestamp or null. - **completedAt** (string | null) - ISO timestamp or null. - **result** (unknown) - Return value from the handler on success. - **error** (string | null) - Error message on failure. ### Response Example ```json { "publicId": "job_123", "status": "completed", "result": { "url": "https://example.com/file.csv" } } ``` ``` -------------------------------- ### Define Configuration with defineConfig Source: https://docs.queuebase.com/guides/configuration Use defineConfig to set up your Queuebase configuration, providing defaults and reading from environment variables. Ensure jobsDir points to your job definitions. ```javascript import { defineConfig } from "@queuebase/nextjs"; // or @queuebase/node export const config = defineConfig({ jobsDir: "./src/jobs", callbackUrl: "http://localhost:3000/api/queuebase", apiUrl: "http://localhost:3847", apiKey: undefined, }); ``` -------------------------------- ### Create Queuebase Client with Direct Configuration Source: https://docs.queuebase.com/guides/creating-a-client Initialize the client with explicit API URL, callback URL, and API key. Ensure `apiKey` is provided in production environments. Imports `createClient` from `@queuebase/nextjs` or `@queuebase/node`. ```typescript import { createClient } from "@queuebase/nextjs"; // or @queuebase/node import { jobs } from "./jobs"; export const jobClient = createClient(jobs, { apiUrl: "http://localhost:3847", callbackUrl: "http://localhost:3000/api/queuebase", apiKey: undefined, // required in production }); ``` -------------------------------- ### Create Queuebase Client with Environment Variables Source: https://docs.queuebase.com/guides/creating-a-client Configure the client using environment variables for `apiUrl`, `apiKey`, and `callbackUrl`. Provides fallback values for local development. This is the recommended approach for production. ```typescript export const jobClient = createClient(jobs, { apiUrl: process.env.QUEUEBASE_API_URL ?? "http://localhost:3847", apiKey: process.env.QUEUEBASE_API_KEY, callbackUrl: process.env.QUEUEBASE_CALLBACK_URL ?? "http://localhost:3000/api/queuebase", }); ``` -------------------------------- ### CI/CD Deployment Step Source: https://docs.queuebase.com/reference/cli Integrate `queuebase generate` and `queuebase sync` into your CI/CD pipeline after building your application to ensure production schedules are up-to-date. The sync command is idempotent. ```bash npx queuebase generate npx queuebase sync ``` -------------------------------- ### Sync Jobs to Production Source: https://docs.queuebase.com/integrations/supastarter Run the sync command to upload your job types and schedules to your Queuebase production environment. This should be done after setting production environment variables. ```bash npx queuebase sync ``` -------------------------------- ### Run development environment Source: https://docs.queuebase.com/guides/dev-server Typical workflow for running the Queuebase dev server and the application concurrently in separate terminals. ```bash # Terminal 1: Queuebase dev server npx queuebase dev # Terminal 2: Your app npm run dev ``` -------------------------------- ### Configuration via defineConfig Source: https://docs.queuebase.com/guides/configuration The defineConfig helper is used to initialize the Queuebase SDK in both Next.js and Node.js environments, allowing for custom job directory and API settings. ```APIDOC ## defineConfig ### Description Initializes the Queuebase configuration. Environment variables take precedence over values passed to this function. ### Parameters #### Request Body - **jobsDir** (string) - Optional - Directory containing job definitions. Default: "./src/jobs" - **callbackUrl** (string) - Optional - Webhook endpoint URL. Default: QUEUEBASE_CALLBACK_URL env var or "http://localhost:3000/api/queuebase" (Next.js only) - **apiUrl** (string) - Optional - Queuebase API endpoint. Default: QUEUEBASE_API_URL env var - **apiKey** (string) - Optional - API key for production. Default: QUEUEBASE_API_KEY env var ### Request Example ```javascript import { defineConfig } from "@queuebase/nextjs"; export const config = defineConfig({ jobsDir: "./src/jobs", callbackUrl: "http://localhost:3000/api/queuebase", apiUrl: "http://localhost:3847", apiKey: undefined, }); ``` ``` -------------------------------- ### Create a Queuebase client Source: https://docs.queuebase.com/getting-started/nodejs Initialize a type-safe client to enqueue jobs, using environment variables for API configuration. ```typescript import { createClient } from "@queuebase/node"; import { jobs } from "./index"; export const jobClient = createClient(jobs, { apiUrl: process.env.QUEUEBASE_API_URL ?? "http://localhost:3847", apiKey: process.env.QUEUEBASE_API_KEY, callbackUrl: process.env.QUEUEBASE_CALLBACK_URL ?? "http://localhost:3000/api/queuebase", }); ``` -------------------------------- ### QueuebaseConfig Source: https://docs.queuebase.com/reference/types Configuration object for initializing Queuebase. ```APIDOC ## QueuebaseConfig Configuration for Queuebase. ### Fields - **jobsDir** (string) - Required - The directory where job definitions are located. - **callbackUrl** (string) - Optional - The URL to send job completion callbacks to. - **apiKey** (string) - Optional - Your Queuebase API key. - **apiUrl** (string) - Optional - The base URL for the Queuebase API. ```typescript interface QueuebaseConfig { jobsDir: string; callbackUrl?: string; apiKey?: string; apiUrl?: string; } ``` ``` -------------------------------- ### Generate the queue manifest Source: https://docs.queuebase.com/guides/dev-server Creates the .queuebase/queuebase.manifest.json file required for syncing scheduled jobs. ```bash npx queuebase generate ``` -------------------------------- ### Create Queuebase Client Source: https://docs.queuebase.com/getting-started/nextjs Initialize the Queuebase client with your job router and configuration, including API URL, API key, and callback URL. This client provides a type-safe way to enqueue jobs. ```typescript import { createClient } from "@queuebase/nextjs"; import { jobs } from "./index"; export const jobClient = createClient(jobs, { apiUrl: process.env.QUEUEBASE_API_URL ?? "http://localhost:3847", apiKey: process.env.QUEUEBASE_API_KEY, callbackUrl: process.env.QUEUEBASE_CALLBACK_URL ?? "http://localhost:3000/api/queuebase", }); ``` -------------------------------- ### Sync Schedule Definitions to Production API Source: https://docs.queuebase.com/reference/cli Use this command to sync schedule definitions from the manifest to the production API. It reads the manifest, extracts jobs with schedules, and posts them to the API. ```bash npx queuebase sync [options] ``` -------------------------------- ### Create a Node.js webhook handler Source: https://docs.queuebase.com/getting-started/nodejs Set up a handler for incoming webhooks, optionally providing a webhook secret for verification. ```typescript import { createNodeHandler } from "@queuebase/node"; import { jobs } from "./jobs"; const handler = createNodeHandler(jobs); // Or pass a webhook secret explicitly (overrides QUEUEBASE_WEBHOOK_SECRET env var) const handler = createNodeHandler(jobs, { webhookSecret: process.env.MY_WEBHOOK_SECRET, }); ``` -------------------------------- ### Schedule Formats Source: https://docs.queuebase.com/guides/scheduled-jobs Demonstrates the different formats accepted by the `schedule` property: Plain English, Raw cron, and Config object. ```APIDOC ## Schedule Formats The `schedule` property accepts three formats: ### Plain English Human-readable expressions that are converted to cron under the hood. ```javascript schedule: "every 5 minutes" schedule: "every hour" schedule: "every 2 hours" schedule: "every day at 9am" schedule: "every weekday at 9am" schedule: "every monday at 2pm" ``` ### Raw cron Standard 5-field cron expressions. ```javascript schedule: "*/5 * * * *" // every 5 minutes schedule: "0 9 * * *" // daily at 9am schedule: "0 9 * * 1-5" // weekdays at 9am ``` ### Config object For full control over timezone and overlap behavior. ```javascript schedule: { cron: "0 9 * * *", timezone: "America/New_York", enabled: true, overlap: "skip", } ``` **Field Descriptions for Config Object:** | Field | Type | Description | Default | |---|---|---|---| | `cron` | `string` | Cron expression or plain English string | (required) | | `timezone` | `string` | IANA timezone | `UTC` | | `enabled` | `boolean` | Whether the schedule is active | `true` | | `overlap` | `'skip' | 'allow'` | What to do if the previous run is still executing | `'skip'` | ``` -------------------------------- ### Create Webhook Handler (App Router) Source: https://docs.queuebase.com/getting-started/nextjs Set up the webhook handler for the App Router using `createHandler`. This endpoint is called by Queuebase to execute jobs. ```typescript import { createHandler } from "@queuebase/nextjs/handler"; import { jobs } from "@/jobs"; export const POST = createHandler(jobs); ``` -------------------------------- ### QueuebaseConfig Interface Source: https://docs.queuebase.com/reference/types Configuration object for initializing Queuebase. ```typescript interface QueuebaseConfig { jobsDir: string; callbackUrl?: string; apiKey?: string; apiUrl?: string; } ``` -------------------------------- ### EnqueueOptions Source: https://docs.queuebase.com/reference/types Options for enqueueing a job. These can be set as defaults on a job definition or passed directly to the `.enqueue()` method. ```APIDOC ## EnqueueOptions Options for enqueueing a job. Can be set as defaults on a job definition or passed to `.enqueue()`. ### Fields - **delay** (string | number) - Optional - Delay before running. Strings: `'5s'`, `'5m'`, `'1h'`, `'2d'`. Numbers: milliseconds. - **retries** (number) - Optional - Number of retry attempts on failure. - **backoff** (BackoffStrategy) - Optional - Backoff strategy for retries. - **backoffDelay** (number) - Optional - Base delay between retries in ms (default: 1000). ```typescript interface EnqueueOptions { delay?: string | number; retries?: number; backoff?: BackoffStrategy; backoffDelay?: number; } ``` ``` -------------------------------- ### POST /enqueue Source: https://docs.queuebase.com/guides/enqueueing-jobs Enqueues a new job into the system with optional configuration for scheduling and retries. ```APIDOC ## POST /enqueue ### Description Enqueues a job validated against the job's schema. Returns a jobId and a getStatus function. ### Request Body - **input** (object) - Required - The job data validated against the schema. - **options** (object) - Optional - Configuration for the job execution. - **delay** (string | number) - Optional - Delay before running (e.g., '5s', 5000). - **retries** (number) - Optional - Number of retry attempts on failure. - **backoff** ('linear' | 'exponential') - Optional - Backoff strategy for retries. - **backoffDelay** (number) - Optional - Base delay between retries in ms. ### Response #### Success Response (200) - **jobId** (string) - Unique job ID. - **getStatus** (function) - A function that returns a Promise resolving to JobStatusResponse. ### Request Example ```javascript await jobClient.sendEmail.enqueue( { to: "user@example.com", subject: "Hi", body: "Hello" }, { delay: "5m", retries: 5, backoff: "exponential", backoffDelay: 2000, } ); ``` ``` -------------------------------- ### Create Webhook Handler Source: https://docs.queuebase.com/integrations/supastarter Set up the API endpoint that Queuebase will call to execute your jobs. This handler processes incoming job execution requests. ```typescript import { createHandler } from "@queuebase/nextjs/handler"; import { jobs } from "@repo/jobs"; export const POST = createHandler(jobs); ``` -------------------------------- ### Manifest File Structure Source: https://docs.queuebase.com/reference/cli The generated manifest file defines job names and their schedule configurations, including cron expressions, timezones, and concurrency settings. ```json { "version": 1, "generatedAt": "2026-03-16T12:00:00.000Z", "jobs": { "sendEmail": {}, "dailyReport": { "schedule": { "cronExpression": "0 9 * * *", "timezone": "UTC", "enabled": true, "overlap": "skip" } } } } ``` -------------------------------- ### Integrate with Fastify Source: https://docs.queuebase.com/getting-started/nodejs Pass the raw request and reply objects to the Queuebase handler. ```typescript import Fastify from "fastify"; import { createNodeHandler } from "@queuebase/node"; import { jobs } from "./jobs"; const fastify = Fastify(); const handler = createNodeHandler(jobs); fastify.post("/api/queuebase", (req, reply) => { handler(req.raw, reply.raw); }); ``` -------------------------------- ### Preview Sync Changes with Dry Run Source: https://docs.queuebase.com/reference/cli The `--dry-run` flag allows you to preview the changes that would be applied to the production API without making any actual modifications. It shows what would be inserted, updated, or deleted. ```bash npx queuebase sync --dry-run ``` -------------------------------- ### Queuebase Environment Variables Source: https://docs.queuebase.com/integrations/supastarter Set environment variables for Queuebase development and production. Ensure API URLs and callback URLs are correctly configured. ```dotenv # Development (defaults work out of the box) QUEUEBASE_API_URL=http://localhost:3847 QUEUEBASE_CALLBACK_URL=http://localhost:3000/api/queuebase # Production QUEUEBASE_API_URL=https://api.queuebase.com QUEUEBASE_API_KEY=your_api_key QUEUEBASE_CALLBACK_URL=https://your-app.com/api/queuebase ``` -------------------------------- ### Define jobs with createJobRouter Source: https://docs.queuebase.com/getting-started/nodejs Create a job router using Zod for input validation and define job handlers with retry configurations. ```typescript import { createJobRouter, job } from "@queuebase/node"; import { z } from "zod"; export const jobs = createJobRouter({ sendEmail: job({ input: z.object({ to: z.string().email(), subject: z.string(), body: z.string(), }), handler: async ({ input, jobId, attempt }) => { console.info(`[job ${jobId}] Sending email to ${input.to} (attempt ${attempt})`); // your email sending logic here return { sent: true }; }, defaults: { retries: 3, backoff: "exponential", }, }), }); export type JobRouter = typeof jobs; ``` -------------------------------- ### Mixing Scheduled and On-Demand Jobs Source: https://docs.queuebase.com/guides/scheduled-jobs Illustrates how to define both scheduled and on-demand jobs within the same Queuebase job router. ```APIDOC ## Mixing Scheduled and On-Demand Jobs A router can contain both scheduled and on-demand jobs: ```javascript export const jobs = createJobRouter({ // On-demand: enqueued by your app code sendEmail: job({ input: z.object({ to: z.string().email(), subject: z.string() }), handler: async ({ input }) => { // send email... return { sent: true }; }, }), // Scheduled: runs automatically cleanupExpired: job({ input: z.object({}), handler: async () => { // cleanup logic... return { cleaned: true }; }, schedule: "every hour", }), }); ``` ``` -------------------------------- ### Enqueue a job Source: https://docs.queuebase.com/guides/enqueueing-jobs Basic syntax for enqueueing a job. The input is validated against the job schema upon execution. ```javascript const { jobId, getStatus } = await jobClient.myJob.enqueue(input, options?); ``` -------------------------------- ### ScheduleConfig Interface Source: https://docs.queuebase.com/reference/types Full configuration object for scheduling jobs, including cron expression and timezone. ```typescript interface ScheduleConfig { cron: string; timezone?: string; enabled?: boolean; overlap?: OverlapPolicy; } ``` -------------------------------- ### Define a Job Router Source: https://docs.queuebase.com/guides/defining-jobs Use createJobRouter and job to define a collection of jobs with schema-validated inputs. ```typescript import { createJobRouter, job } from "@queuebase/nextjs"; // or @queuebase/node import { z } from "zod"; // or valibot, arktype, etc. export const jobs = createJobRouter({ myJob: job({ input: z.object({ /* your schema */ }), handler: async (ctx) => { /* returns output */ }, defaults: { /* optional EnqueueOptions */ }, }), }); ``` -------------------------------- ### JobDefinition Source: https://docs.queuebase.com/reference/types Defines a job with typed input and output, including its handler, default options, configuration, and schedule. ```APIDOC ## JobDefinition A job definition with typed input and output. The `input` field accepts any Standard Schema-compatible validator (Zod, Valibot, ArkType, etc.). ### Fields - **input** (StandardSchemaV1) - Required - The schema for the job's input. - **handler** ((ctx: JobContext) => Promise) - Required - The function that executes the job logic. - **defaults** (EnqueueOptions) - Optional - Default enqueue options for this job. - **config** (JobTypeConfig) - Optional - Configuration for timeout and concurrency. - **schedule** (ScheduleInput) - Optional - Schedule configuration for the job (only when TInput is Record). ```typescript interface JobDefinition { input: StandardSchemaV1; handler: (ctx: JobContext) => Promise; defaults?: EnqueueOptions; config?: JobTypeConfig; schedule?: ScheduleInput; // only when TInput is Record } ``` ``` -------------------------------- ### ScheduleConfig Source: https://docs.queuebase.com/reference/types Full schedule configuration object for defining cron-based job execution. ```APIDOC ## ScheduleConfig Full schedule configuration object. ### Fields - **cron** (string) - Required - Cron expression or plain English string. - **timezone** (string) - Optional - IANA timezone (default: `'UTC'`). - **enabled** (boolean) - Optional - Whether the schedule is active (default: `true`). - **overlap** (OverlapPolicy) - Optional - Behavior when previous run is still executing (default: `'skip'`). ```typescript interface ScheduleConfig { cron: string; timezone?: string; enabled?: boolean; overlap?: OverlapPolicy; } ``` ``` -------------------------------- ### Define Jobs with Zod Validation Source: https://docs.queuebase.com/getting-started/nextjs Create a job router using `createJobRouter` and define individual jobs with input validation using Zod schemas. The handler function receives job context and input. ```typescript import { createJobRouter, job } from "@queuebase/nextjs"; import { z } from "zod"; export const jobs = createJobRouter({ sendEmail: job({ input: z.object({ to: z.string().email(), subject: z.string(), body: z.string(), }), handler: async ({ input, jobId, attempt }) => { console.info(`[job ${jobId}] Sending email to ${input.to} (attempt ${attempt})`); // your email sending logic here return { sent: true }; }, defaults: { retries: 3, backoff: "exponential", }, }), }); export type JobRouter = typeof jobs; ``` -------------------------------- ### Integrate with Express Source: https://docs.queuebase.com/getting-started/nodejs Use express.raw to bypass JSON parsing for the webhook route, ensuring correct signature verification. ```typescript import express from "express"; import { createNodeHandler } from "@queuebase/node"; import { jobs } from "./jobs"; const app = express(); const handler = createNodeHandler(jobs); app.post("/api/queuebase", express.raw({ type: "*/*" }), (req, res) => { handler(req, res); }); ``` -------------------------------- ### Define Jobs with Input Validation Source: https://docs.queuebase.com/integrations/supastarter Create a job router with schemas for type-safe input validation and handlers for job execution logic. Supports Zod or any Standard Schema-compatible library. ```typescript import { createJobRouter, job } from "@queuebase/nextjs"; import { z } from "zod"; export const jobs = createJobRouter({ sendWelcomeEmail: job({ input: z.object({ to: z.string().email(), name: z.string(), }), handler: async ({ input, jobId, attempt }) => { // your email sending logic here console.info(`[job ${jobId}] Sending welcome email to ${input.to}`); return { sent: true }; }, defaults: { retries: 3, backoff: "exponential", }, }), processSubscription: job({ input: z.object({ userId: z.string(), plan: z.enum(["free", "pro", "enterprise"]), }), handler: async ({ input, jobId }) => { // subscription processing logic console.info(`[job ${jobId}] Processing ${input.plan} subscription for ${input.userId}`); return { processed: true }; }, }), }); export type JobRouter = typeof jobs; ``` -------------------------------- ### ScheduleInput Source: https://docs.queuebase.com/reference/types Represents the input for scheduling a job. This can be a string or a ScheduleConfig object. ```APIDOC ## ScheduleInput Schedule configuration for a job. Only available on jobs with an empty input schema. When a string, it can be a plain English expression (`"every day at 9am"`) or a raw cron expression (`"0 9 * * *"`). ```typescript type ScheduleInput = string | ScheduleConfig; ``` ``` -------------------------------- ### Enqueue a Job Source: https://docs.queuebase.com/getting-started/nextjs Enqueue a job from a server action, route handler, or any server-side context using the `jobClient`. The SDK validates input, sends the job to the Queuebase API, and returns a `jobId`. ```typescript "use server"; import { jobClient } from "@/jobs/client"; export async function sendWelcomeEmail(to: string) { const { jobId } = await jobClient.sendEmail.enqueue({ to, subject: "Welcome", body: "Hello!", }); return jobId; } ``` -------------------------------- ### JobStatus Source: https://docs.queuebase.com/reference/types Represents the possible states of a job within the Queuebase system. ```APIDOC ## JobStatus Represents the possible states of a job within the Queuebase system. ```typescript type JobStatus = 'pending' | 'running' | 'completed' | 'failed' | 'cancelled'; ``` ``` -------------------------------- ### BackoffStrategy Source: https://docs.queuebase.com/reference/types Defines the strategy used for retrying failed jobs. ```APIDOC ## BackoffStrategy Defines the strategy used for retrying failed jobs. ```typescript type BackoffStrategy = 'linear' | 'exponential'; ``` ``` -------------------------------- ### Create Webhook Handler (Pages Router) Source: https://docs.queuebase.com/getting-started/nextjs Configure the webhook handler for the Pages Router using `createPagesHandler`. It's crucial to disable the built-in body parser to ensure correct webhook signature verification. ```typescript import { createPagesHandler } from "@queuebase/nextjs/pages"; import { jobs } from "@/jobs"; export const config = { api: { bodyParser: false } }; export default createPagesHandler(jobs); ``` -------------------------------- ### JobTypeConfig Source: https://docs.queuebase.com/reference/types Per-job-type configuration for timeout and concurrency limits. ```APIDOC ## JobTypeConfig Per-job-type configuration for timeout and concurrency. ### Fields - **timeout** (string | number) - Optional - Max execution time (`'5m'`, `'30s'`, or milliseconds). - **concurrency** (number) - Optional - Max concurrent executions of this job type per worker. ```typescript interface JobTypeConfig { timeout?: string | number; concurrency?: number; } ``` ``` -------------------------------- ### EnqueueResult Source: https://docs.queuebase.com/reference/types The result returned after successfully enqueuing a job. ```APIDOC ## EnqueueResult Returned from `.enqueue()`. ### Fields - **jobId** (string) - The unique ID of the enqueued job. - **getStatus** (() => Promise) - A function to retrieve the current status of the enqueued job. ```typescript interface EnqueueResult { jobId: string; getStatus: () => Promise; } ``` ``` -------------------------------- ### EnqueueOptions Interface Source: https://docs.queuebase.com/reference/types Options for enqueueing a job, which can be set as defaults or passed directly. ```typescript interface EnqueueOptions { delay?: string | number; retries?: number; backoff?: BackoffStrategy; backoffDelay?: number; } ``` -------------------------------- ### ScheduleInput Type Source: https://docs.queuebase.com/reference/types Input type for scheduling jobs, accepting either a string or a configuration object. ```typescript type ScheduleInput = string | ScheduleConfig; ``` -------------------------------- ### JobContext Source: https://docs.queuebase.com/reference/types Context object passed to job handlers, providing input, job details, and control functions. ```APIDOC ## JobContext Context passed to job handlers. ### Fields - **input** (TInput) - The validated input data for the job. - **jobId** (string) - Unique identifier for the job. - **attempt** (number) - The current attempt number (1-indexed). - **maxAttempts** (number) - The maximum number of attempts allowed for this job. - **fail** ((reason: string) => never) - A function to explicitly mark the job as failed. See Defining Jobs. ```typescript interface JobContext { input: TInput; jobId: string; attempt: number; maxAttempts: number; fail: (reason: string) => never; } ``` ``` -------------------------------- ### JobDefinition Interface Source: https://docs.queuebase.com/reference/types Defines a job with typed input and output, including handler, defaults, and schedule. ```typescript interface JobDefinition { input: StandardSchemaV1; handler: (ctx: JobContext) => Promise; defaults?: EnqueueOptions; config?: JobTypeConfig; schedule?: ScheduleInput; // only when TInput is Record } ``` -------------------------------- ### Enqueue a Job Source: https://docs.queuebase.com/integrations/supastarter Enqueue a job using the type-safe client. The SDK validates input at compile and runtime, sends the job to the Queuebase API, and returns a jobId for tracking. ```typescript "use server"; import { jobClient } from "@repo/jobs/client"; export async function sendWelcomeEmail(to: string, name: string) { const { jobId } = await jobClient.sendWelcomeEmail.enqueue({ to, name, }); return jobId; } ``` -------------------------------- ### Configure Job Defaults Source: https://docs.queuebase.com/guides/defining-jobs Set default enqueue options like retries and backoff strategies within the job definition. ```typescript sendEmail: job({ input: z.object({ to: z.string().email() }), handler: async ({ input }) => { // ... return { sent: true }; }, defaults: { retries: 3, backoff: "exponential", backoffDelay: 2000, }, }), ``` -------------------------------- ### JobTypeConfig Interface Source: https://docs.queuebase.com/reference/types Configuration for job types, specifying timeout and concurrency limits. ```typescript interface JobTypeConfig { timeout?: string | number; concurrency?: number; } ``` -------------------------------- ### ResolvedSchedule Source: https://docs.queuebase.com/reference/types Internal normalized form of a schedule after parsing and validation. ```APIDOC ## ResolvedSchedule Internal normalized form of a schedule after parsing and validation. ```typescript interface ResolvedSchedule { cronExpression: string; timezone: string; enabled: boolean; overlap: OverlapPolicy; } ``` ``` -------------------------------- ### JobStatus Type Source: https://docs.queuebase.com/reference/types Represents the possible states of a job within the Queuebase system. ```typescript type JobStatus = 'pending' | 'running' | 'completed' | 'failed' | 'cancelled'; ``` -------------------------------- ### Enqueue a job Source: https://docs.queuebase.com/getting-started/nodejs Trigger a job execution by calling the enqueue method on the client. ```typescript import { jobClient } from "./jobs/client"; app.post("/send-email", async (req, res) => { const { jobId } = await jobClient.sendEmail.enqueue({ to: req.body.to, subject: "Welcome", body: "Hello!", }); res.json({ jobId }); }); ``` -------------------------------- ### BackoffStrategy Type Source: https://docs.queuebase.com/reference/types Defines the strategies available for retrying failed jobs. ```typescript type BackoffStrategy = 'linear' | 'exponential'; ``` -------------------------------- ### Mix scheduled and on-demand jobs Source: https://docs.queuebase.com/guides/scheduled-jobs A single job router can contain both on-demand jobs with input schemas and scheduled jobs with empty schemas. ```typescript export const jobs = createJobRouter({ // On-demand: enqueued by your app code sendEmail: job({ input: z.object({ to: z.string().email(), subject: z.string() }), handler: async ({ input }) => { // send email... return { sent: true }; }, }), // Scheduled: runs automatically cleanupExpired: job({ input: z.object({}), handler: async () => { // cleanup logic... return { cleaned: true }; }, schedule: "every hour", }), }); ``` -------------------------------- ### Define a Daily Cleanup Scheduled Job Source: https://docs.queuebase.com/integrations/supastarter Define a scheduled job with a plain English schedule. The input schema must be empty for scheduled jobs. ```typescript import { createJobRouter, job } from "@queuebase/nextjs"; import { z } from "zod"; export const jobs = createJobRouter({ // ... your other jobs dailyCleanup: job({ input: z.object({}), schedule: "every day at 2am", handler: async ({ jobId }) => { // cleanup expired sessions, old data, etc. console.info(`[job ${jobId}] Running daily cleanup`); return { cleaned: true }; }, }), }); ``` -------------------------------- ### JobStatusResponse Source: https://docs.queuebase.com/reference/types Represents the status of a job as returned by the Queuebase API. ```APIDOC ## JobStatusResponse Job status as returned by the API. ### Fields - **publicId** (string) - The public-facing ID of the job. - **name** (string) - The name of the job type. - **status** (JobStatus) - The current status of the job. - **attempt** (number) - The current attempt number. - **maxAttempts** (number) - The maximum number of attempts allowed. - **createdAt** (string) - The timestamp when the job was created. - **startedAt** (string | null) - The timestamp when the job started execution, or null if not started. - **completedAt** (string | null) - The timestamp when the job completed execution, or null if not completed. - **result** (unknown) - The result of the job execution, if completed successfully. - **error** (string | null) - An error message if the job failed, or null otherwise. ```typescript interface JobStatusResponse { publicId: string; name: string; status: JobStatus; attempt: number; maxAttempts: number; createdAt: string; startedAt: string | null; completedAt: string | null; result: unknown; error: string | null; } ``` ``` -------------------------------- ### Schedule Recurring Jobs Source: https://docs.queuebase.com/guides/defining-jobs Define a schedule property on a job with an empty input schema to run tasks on a cron schedule. ```typescript cleanupExpired: job({ input: z.object({}), handler: async () => { // runs every hour return { cleaned: true }; }, schedule: "every hour", }), ``` -------------------------------- ### Configure Scheduled Job with Timezone and Overlap Source: https://docs.queuebase.com/integrations/supastarter Configure a scheduled job with a cron expression, timezone, and overlap strategy. Use this for more precise control over job execution. ```typescript schedule: { cron: "every day at 2am", timezone: "America/New_York", overlap: "skip", } ``` -------------------------------- ### Access Job Context Source: https://docs.queuebase.com/guides/defining-jobs The handler receives a JobContext object containing input, metadata, and control methods. ```typescript handler: async ({ input, jobId, attempt, maxAttempts }) => { console.log(`Job ${jobId}, attempt ${attempt}/${maxAttempts}`); // use input (fully typed from your schema) return { success: true }; } ``` -------------------------------- ### InferJobInput Source: https://docs.queuebase.com/reference/type-utilities Extracts the input type from a job definition's schema. ```APIDOC ## InferJobInput ### Description Extracts the input type from a job definition's schema. ### Usage ```typescript import type { InferJobInput } from "@queuebase/nextjs"; type EmailInput = InferJobInput; // Expected type: { to: string; subject: string; body: string } ``` ``` -------------------------------- ### Extract job input type with InferJobInput Source: https://docs.queuebase.com/reference/type-utilities Use this utility to extract the input schema type from a job definition. Useful for maintaining type safety in shared modules. ```typescript import type { InferJobInput } from "@queuebase/nextjs"; type EmailInput = InferJobInput; // { to: string; subject: string; body: string } ``` -------------------------------- ### JobContext Interface Source: https://docs.queuebase.com/reference/types Contextual information passed to job handlers during execution. ```typescript interface JobContext { input: TInput; jobId: string; attempt: number; maxAttempts: number; fail: (reason: string) => never; } ``` -------------------------------- ### InferJobOutput Source: https://docs.queuebase.com/reference/type-utilities Extracts the return type from a job definition's handler. ```APIDOC ## InferJobOutput ### Description Extracts the return type from a job definition's handler. ### Usage ```typescript import type { InferJobOutput } from "@queuebase/nextjs"; type EmailOutput = InferJobOutput; // Expected type: { sent: boolean } ``` ``` -------------------------------- ### JobStatusResponse Interface Source: https://docs.queuebase.com/reference/types Represents the status of a job as returned by the API. ```typescript interface JobStatusResponse { publicId: string; name: string; status: JobStatus; attempt: number; maxAttempts: number; createdAt: string; startedAt: string | null; completedAt: string | null; result: unknown; error: string | null; } ``` -------------------------------- ### ResolvedSchedule Interface Source: https://docs.queuebase.com/reference/types Internal representation of a schedule after parsing and validation. ```typescript interface ResolvedSchedule { cronExpression: string; timezone: string; enabled: boolean; overlap: OverlapPolicy; } ``` -------------------------------- ### EnqueueResult Interface Source: https://docs.queuebase.com/reference/types The result returned after successfully enqueueing a job. ```typescript interface EnqueueResult { jobId: string; getStatus: () => Promise; } ``` -------------------------------- ### Extract job output type with InferJobOutput Source: https://docs.queuebase.com/reference/type-utilities Use this utility to extract the return type of a job handler. Ideal for defining API response types based on job results. ```typescript import type { InferJobOutput } from "@queuebase/nextjs"; type EmailOutput = InferJobOutput; // { sent: boolean } ``` -------------------------------- ### JobResult Source: https://docs.queuebase.com/reference/types Represents the outcome of a job execution, indicating success or failure. ```APIDOC ## JobResult Result of a job execution. ### Fields - **success** (boolean) - Indicates whether the job execution was successful. - **output** (TOutput) - Optional - The output of the job if successful. - **error** (string) - Optional - An error message if the job failed. - **duration** (number) - The duration of the job execution in milliseconds. ```typescript interface JobResult { success: boolean; output?: TOutput; error?: string; duration: number; } ``` ``` -------------------------------- ### Define a scheduled job Source: https://docs.queuebase.com/guides/scheduled-jobs Scheduled jobs are defined within a job router using the schedule property. The input schema must be empty. ```typescript import { createJobRouter, job } from "@queuebase/nextjs"; import { z } from "zod"; export const jobs = createJobRouter({ dailyReport: job({ input: z.object({}), handler: async ({ jobId }) => { // runs every day at 9am UTC return { generated: true }; }, schedule: "every day at 9am", }), }); ``` -------------------------------- ### Explicitly Fail a Job Source: https://docs.queuebase.com/guides/defining-jobs Call ctx.fail() to mark a job as failed with a specific reason, which halts execution of subsequent code. ```typescript handler: async ({ input, fail }) => { const user = await findUser(input.userId); if (!user) { fail("User not found"); } // this only runs if user exists await sendEmail(user.email); return { sent: true }; } ``` -------------------------------- ### JobResult Interface Source: https://docs.queuebase.com/reference/types The outcome of a job's execution, indicating success or failure. ```typescript interface JobResult { success: boolean; output?: TOutput; error?: string; duration: number; } ``` -------------------------------- ### OverlapPolicy Source: https://docs.queuebase.com/reference/types Defines the policy for handling overlapping job executions. ```APIDOC ## OverlapPolicy ```typescript type OverlapPolicy = 'skip' | 'allow'; ``` ``` -------------------------------- ### Check job status Source: https://docs.queuebase.com/guides/enqueueing-jobs Polling mechanism to track job progress using the getStatus function returned from the enqueue call. ```javascript const { jobId, getStatus } = await jobClient.generateExport.enqueue({ type: "CSV", }); const poll = setInterval(async () => { const status = await getStatus(); if (status.status === "completed") { clearInterval(poll); const downloadUrl = (status.result as { url: string }).url; // show download link } if (status.status === "failed") { clearInterval(poll); // show error: status.error } }, 1000); ``` -------------------------------- ### OverlapPolicy Type Source: https://docs.queuebase.com/reference/types Defines the behavior when a scheduled job overlaps with a previous execution. ```typescript type OverlapPolicy = 'skip' | 'allow'; ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.