vercel-local-cron
v0.1.0
Published
Run Vercel cron jobs locally during Next.js development
Maintainers
Readme
Vercel Local Cron
Run Vercel cron jobs locally during Next.js development
A lightweight TypeScript library that automatically executes Vercel cron jobs on your local machine during npm run dev. No more manual testing or deploying to preview environments just to test your cron jobs!
Features
- ✅ Automatic Scheduling - Reads
vercel.jsonand schedules cron jobs locally - 🔒 Authentication - Includes
CRON_SECRETfrom.env.localin requests - 🚀 Zero Configuration - Works out of the box with Next.js projects
- 🎯 Port Detection - Automatically detects the Next.js dev server port
- 🧹 Clean Shutdown - Gracefully stops all jobs when you stop the dev server
- 📝 TypeScript Support - Fully typed with comprehensive type definitions
Installation
npm install vercel-local-cron --save-dev
# or
yarn add -D vercel-local-cron
# or
pnpm add -D vercel-local-cronQuick Start
1. Install in Your Project
Run the install command to automatically configure your project:
npx vercel-local-cron installThis will:
- Install
vercel-local-cronas a dev dependency - Update your
package.jsondev script to usevercel-local-cron run
2. Define Cron Jobs in vercel.json
Create a vercel.json file in your project root:
{
"$schema": "https://openapi.vercel.sh/vercel.json",
"crons": [
{
"path": "/api/cron/cleanup",
"schedule": "0 0 * * *"
},
{
"path": "/api/cron/send-emails",
"schedule": "*/15 * * * *"
}
]
}3. Add CRON_SECRET to .env.local
CRON_SECRET=your-secret-token-here4. Start Development
npm run devThat's it! Your cron jobs will now execute on schedule during development.
How It Works
- Starts Next.js - Spawns
next devand monitors the output - Detects Port - Automatically detects which port Next.js is running on
- Schedules Jobs - Reads
vercel.jsonand schedules cron jobs using Croner - Executes Requests - Makes authenticated HTTP GET requests to your endpoints on schedule
- Clean Shutdown - Stops all jobs when you press Ctrl+C
Configuration
Environment Variables
The library looks for environment files in this order:
.env.local(highest priority).env.development.env
Supported variables:
CRON_SECRET- Secret token included in Authorization headerPORT- Custom port (if Next.js doesn't auto-detect)
vercel.json Structure
{
"crons": [
{
"path": "/api/cron/my-job",
"schedule": "0 0 * * *"
}
]
}Cron Expression Format:
* * * * *
│ │ │ │ │
│ │ │ │ └─── Day of week (0-7, Sunday = 0 or 7)
│ │ │ └───── Month (1-12)
│ │ └─────── Day of month (1-31)
│ └───────── Hour (0-23)
└─────────── Minute (0-59)Common Examples:
0 0 * * *- Daily at midnight*/15 * * * *- Every 15 minutes0 */2 * * *- Every 2 hours0 9 * * 1- Every Monday at 9 AM
CLI Commands
install
Automatically install and configure vercel-local-cron in your project:
npx vercel-local-cron installThis command:
- Detects your package manager (npm, yarn, pnpm, or bun)
- Installs vercel-local-cron as a dev dependency
- Updates your
package.jsondev script tovercel-local-cron run
run
Run the cron scheduler with Next.js dev server:
vercel-local-cron runThis is what gets executed when you run npm run dev after installation.
help
Show help message with available commands:
vercel-local-cron helpAPI Usage
You can also use the library programmatically:
import { CronScheduler, parseVercelConfig, runDev, installCommand } from 'vercel-local-cron';
// Run the dev server programmatically
await runDev();
// Or use individual components
const vercelConfig = await parseVercelConfig();
const scheduler = new CronScheduler({
port: 3000,
cronSecret: process.env.CRON_SECRET,
jobs: vercelConfig.crons || [],
});
// Stop all jobs later
scheduler.stop();Example API Route
Here's how to secure your cron endpoints in Next.js:
// app/api/cron/cleanup/route.ts
import { NextRequest, NextResponse } from 'next/server';
export async function GET(request: NextRequest) {
// Verify the request is from a cron job
const authHeader = request.headers.get('authorization');
const cronSecret = process.env.CRON_SECRET;
if (!cronSecret || authHeader !== `Bearer ${cronSecret}`) {
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
}
// Your cron job logic here
console.log('Running cleanup job...');
return NextResponse.json({ success: true });
}Troubleshooting
Port Not Detected
If the port isn't automatically detected, you can:
Set PORT environment variable:
PORT=3000 npx vercel-local-cronCheck Next.js output - The library looks for "ready on" messages
No Cron Jobs Running
- Verify
vercel.jsonexists in your project root - Check that
cronsarray is properly formatted - Look for error messages in the console output
Authorization Errors
- Ensure
CRON_SECRETis set in.env.local - Verify your API route is checking the Authorization header correctly
- The header format is
Bearer <your-secret>
Jobs Not Executing
- Check the console for scheduling confirmation
- Verify the cron expression is valid
- Ensure the API endpoint exists and is accessible
Requirements
- Node.js ≥ 18.0.0
- Next.js 13, 14, or 15
Development
# Install dependencies
npm install
# Build the project
npm run build
# Type check
npm run typecheckLicense
MIT
Contributing
Contributions are welcome! Please feel free to submit issues or pull requests.
Made with ❤️ for Next.js developers
