DocsNext.js

Next.js App Router Setup

1. Environment Setup

Install SDK

Install our node SDK next-cron-node:

npm install next-cron-node

Add Environment Variables

Add the following to your .env file:

NEXT_CRON_API_KEY=...
NEXT_CRON_WEBHOOK_SECRET=...

Replace ... with your API key and webhook secret from the dashboard.

Initialize SDK

Initialize the SDK with your API key:

import { NextCron } from "next-cron-node";
 
const nextCron = new NextCron(process.env.NEXT_CRON_API_KEY!);
 
export default nextCron;

2. Create a Webhook

Create a webhook to handle schedule and cron:

import { constructEvent } from "next-cron-node";
 
export async function POST(req: NextRequest) {
  const text = await req.text();
  const signature = req.headers.get("x-signature");
 
  if (!signature) throw new Error("No signature");
 
  const event = constructEvent(
    text,
    signature,
    process.env.NEXT_CRON_WEBHOOK_SECRET!
  );
 
  if (event.type === "schedule") {
    console.log("Schedule event:", event.data);
  } else if (event.type === "cron") {
    console.log("Cron event:", event.data);
  }
 
  return NextResponse.json(null);
}

3. Create a Schedule

Define a task to run at a specific time:

"use server";
 
import nextCron from "@/lib/next-cron";
 
export const createSchedule = async () => {
  await nextCron.schedule.create({
    name: "My Schedule",
    endpoint: "https://your-site.com/api/next-cron",
    scheduledAt: new Date(Date.now() + 1000 * 5 * 60), // 5 minutes later
    data: JSON.stringify({ userId: "123" }),
    tags: ["tag", "another-tag"],
  });
  console.log("Schedule created.");
};

4. Test the Setup

await createSchedule();

When the schedule runs, your console should log:

{ userId: '123' }