How to Schedule Cron Jobs with Next.JS

Will FPWill FP
3 min read

Background jobs and crons are an essential part of many web applications, but frameworks like Next.JS don’t support them natively due to their serverless nature. However, it is possible to schedule cron jobs using an external service like Rapidcron.

Getting Started

Setting Up Your Environment

First, obtain your API key from the Rapidcron dashboard. Store this key in your Next.js environment variables:

# .env.local
RAPIDCRON_API_KEY=your_api_key_here

Installing the SDK

Install the Rapidcron SDK using your preferred package manager:

# Using npm
npm install rapidcron --save

# Using yarn
yarn add rapidcron

# Using pnpm
pnpm add rapidcron

# Using bun
bun add rapidcron

Implementing Scheduled Tasks in Next.js

Creating a Rapidcron Client

Create a utility file to initialize the Rapidcron client:

// utils/rapidcron.ts
import Rapidcron from "rapidcron";

export const rapidcron = new Rapidcron(process.env.RAPIDCRON_API_KEY!);

Setting Up API Routes for Task Execution

Create an API route that Rapidcron will call when executing tasks:

// app/api/cron/route.ts
import { NextResponse } from 'next/server';

export async function POST(request: Request) {
  try {
    const data = await request.json();

    // Handle your scheduled task logic here
    // For example, cleaning up old data:
    await cleanupOldRecords();

    return NextResponse.json({ success: true });
  } catch (error) {
    console.error('Cron job failed:', error);
    return NextResponse.json({ error: 'Internal Server Error' }, { status: 500 });
  }
}

Creating Different Types of Tasks

Delayed (One-off) Tasks

Perfect for operations that need to run once at a specific time:

// app/api/schedule-task/route.ts
import { rapidcron } from '@/utils/rapidcron';
import { NextResponse } from 'next/server';

export async function POST(request: Request) {
  try {
    await rapidcron.tasks.create({
      type: "delayed",
      nextRunAt: new Date(Date.now() + 1000 * 60 * 60), // 1 hour from now
      request: {
        method: "POST",
        url: `${process.env.NEXT_PUBLIC_APP_URL}/api/cron`,
        headers: {
          "Content-Type": "application/json"
        },
        body: JSON.stringify({
          // Your payload
        })
      }
    });

    return NextResponse.json({ success: true });
  } catch (error) {
    return NextResponse.json({ error: 'Failed to schedule task' }, { status: 500 });
  }
}

Recurring Tasks

For operations that need to run on a schedule:

// app/api/schedule-recurring/route.ts
import { rapidcron } from '@/utils/rapidcron';
import { NextResponse } from 'next/server';

export async function POST(request: Request) {
  try {
    await rapidcron.tasks.create({
      type: "recurring",
      recurrencePattern: "0 0 * * *", // Run daily at midnight
      request: {
        method: "POST",
        url: `${process.env.NEXT_PUBLIC_APP_URL}/api/cron`,
        headers: {
          "Content-Type": "application/json"
        },
        body: JSON.stringify({
          // Your payload
        })
      }
    });

    return NextResponse.json({ success: true });
  } catch (error) {
    return NextResponse.json({ error: 'Failed to schedule recurring task' }, { status: 500 });
  }
}

Common Use Cases in Next.js Applications

  • Data Cleanup: Regularly clean up old or temporary data

  • Cache Management: Schedule cache invalidation or updates

  • Report Generation: Generate periodic reports or analytics

  • Email Campaigns: Schedule email dispatches

  • Database Maintenance: Run database optimizations or backups

  • Content Updates: Schedule content publishing or updates

Security Considerations

  1. API Route Protection:

    • Implement authentication for your cron endpoints

    • Use environment variables for sensitive configuration

    • Consider using webhook signatures for verification

  2. Error Handling:

    • Implement proper logging for debugging

    • Set up error notifications for failed jobs

    • Handle retries appropriately

Conclusion

Integrating Rapidcron with Next.js provides a robust solution for handling scheduled tasks in your web application. By following the patterns and practices outlined in this guide, you can implement reliable background jobs while maintaining the serverless nature of your Next.js application.

Remember to:

  • Keep your API keys secure

  • Monitor task execution through the Rapidcron dashboard

  • Implement proper error handling

  • Use TypeScript for better type safety

  • Follow Next.js best practices for API routes and server components

For more information about cron expressions and advanced features, visit the Rapidcron documentation.

Happy scheduling!

0
Subscribe to my newsletter

Read articles from Will FP directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Will FP
Will FP