Next.js Pages 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 (using the /pages directory) 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
QUEUEBASE_URL=... # Your app URL
Creating the job router
1. Create the job router
Jobs in Queuebase are associated with a route. Below is a simple example of creating a job router.
// api/queuebase.ts
import { type JobRouter as QueuebaseJobRouter } from "queuebase/lib/types";
import { createQueuebase } from "queuebase/next";
export const jobRouter = {
sayHello: j().handler(() => {
console.log("Hello there!");
}),
} satisfies QueuebaseJobRouter;
export type JobRouter = typeof jobRouter;
2. Create the API route
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.ts
import { createPagesApiHandler } from "queuebase/next";
const handler = createPagesApiHandler({
router: jobRouter,
});
export default handler;
3. Setup the job client
The createQueuebaseClient
helper method takes your router and creates a jobs
object. This object contains all your jobs defined in your router and allows you to trigger them. Oh, and did we mention it's completely type-safe?
// utils/queuebase.ts
import type { JobRouter } from "@/pages/api/queuebase";
import { createQueuebaseClient } from "queuebase/client";
export const { jobs } = createQueuebaseClient<JobRouter>({
apiKey: process.env.NEXT_PUBLIC_QUEUEBASE_API_KEY!,
});
Running jobs
To run a job, you can use the enqueue
method on the job object.
// components/execute-job.tsx
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
</button>
);
}