Cron Job
Set up cron jobs in ShipAhead to schedule automated tasks like sending reminder emails.
Tools Used
- cron-job.org: Free external service to schedule jobs by calling your API endpoints.
Setup & Configuration
Set CRON_SECRET
- Set an environment variable to protect your cron endpoints:
.env.local
CRON_SECRET="your-secret-key" - The secret key can be anything you type yourself (e.g., a long random string), or you can generate one using a password generator.
- Set an environment variable to protect your cron endpoints:
Use ShipAhead’s Built-in API Endpoint
- Each job lives in
/server/jobs/(e.g.,sendReminderEmails.js). - Trigger them via
/api/cron/[job].
Example:Codehttps://your-site.com/api/cron/sendReminderEmails
- Each job lives in
Create a Cron Job on cron-job.org
- Go to cron-job.org and create an account.
- Add a New Cron Job:
- URL:
https://your-site.com/api/cron/sendReminderEmails - Execution schedule: e.g.,
0 8 * * *(runs daily at 8 AM).
- URL:
- Under Advanced → HTTP Headers, add:
Code
X-Cron-Secret: your-secret-key
Usage
Run Existing Jobs
ShipAhead includes an example job:/server/jobs/sendReminderEmails.js
Triggered athttps://your-site.com/api/cron/sendReminderEmails.Create New Jobs
- Add a new job file in
/server/jobs/:javascript// server/jobs/myNewJob.js export async function myNewJob() { console.log('[CRON] Running my new job...'); // Add your logic here (e.g., update database, send notifications) } - Trigger it via endpoint:
Code
https://your-site.com/api/cron/myNewJob - Configure a cron-job.org schedule with the same URL and add the
X-Cron-Secretheader.
- Add a new job file in
Verify Jobs
- Check server logs for
[CRON]messages. - Or test your API endpoint directly with the header:
bash
curl -H "X-Cron-Secret: your-secret-key" https://your-site.com/api/cron/myNewJob
- Check server logs for
Why cron-job.org?
- No need to install
node-cronor run background workers. - Works with serverless platforms like Vercel, Netlify, or Cloudflare.
- Secure with your custom
X-Cron-Secret.