Next.js App Router
Prequistisites
Before getting started with Queuebase, make sure you have the following setup.
- A Queuebase account (sign up here (opens in a new tab)) with an app
- A Next.js application
- Ngrok (opens in a new tab) or Localtunnel (opens in a new tab) (to expose your local environment to the internet)
Setting up your environment
1. Install packages
npm i queuebase zod
2. Add environment variables
You can get these from the Queuebase dashboard.
# .env.local
NEXT_PUBLIC_QUEUEBASE_API_KEY=... # Your Queuebase API key
QUEUEBASE_SECRET_KEY=... # Your Queuebase secret key
Creating the job router
1. Create the job router
All jobs in Queuebase are associated with a route. The example below is a very simple of example of creating a job router.
// api/queuebase/core.ts
import { type JobRouter as QueuebaseJobRouter } from "queuebase/lib/types";
import { createQueuebase } from "queuebase/next";
import { z } from "zod";
export const jobRouter = {
sayHello: j().handler(() => {
console.log("Hello there!");
}),
} satisfies QueuebaseJobRouter;
export type JobRouter = typeof jobRouter;
2. Create the route handler
When a job is triggered, Queuebase will send a POST request to this endpoint with the job name and any job parameters needed. This route MUST match the route you defined in the dashboard.
// api/queuebase/route.ts
import { createAppRouteHandler } from "queuebase/next";
import { jobRouter } from "./core";
export const { GET, POST } = createAppRouteHandler({
router: jobRouter,
});
3. Setup the job client
Here's where the magic happens. The jobs
object contains all your jobs defined in your router and allows you trigger them. Oh, and did we mention it's completely type-safe?
// utils/queuebase.ts
import type { JobRouter } from "@/app/api/queuebase/core";
import { createQueuebaseClient } from "queuebase/client";
export const { jobs } = createQueuebaseClient<JobRouter>({
apiKey: process.env.NEXT_PUBLIC_QUEUEBASE_API_KEY!,
});
Run your jobs
To run a job, you can use the enqueue
method on the job object.
Client Component
// app/execute-job.tsx
"use client";
import { jobs } from "@/utils/queuebase";
export default function ExecuteJob() {
return (
<button
className="px h-10 rounded-md border bg-emerald-600 px-4 py-2 text-white"
onClick={async () => {
await jobs("sayHello").enqueue();
}}>
Execute job without input
</button>
);
}
Server Action
"use server";
import { jobs } from "@/utils/queuebase";
export default async function executeServer() {
await jobs("sayHello").enqueue();
}