Logo

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

  1. 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.
  2. Use ShipAhead’s Built-in API Endpoint

    • Each job lives in /server/jobs/ (e.g., sendReminderEmails.js).
    • Trigger them via /api/cron/[job].
      Example:
      Code
      https://your-site.com/api/cron/sendReminderEmails
  3. 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).
    • 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 at https://your-site.com/api/cron/sendReminderEmails.

  • Create New Jobs

    1. 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)
      }
    2. Trigger it via endpoint:
      Code
      https://your-site.com/api/cron/myNewJob
    3. Configure a cron-job.org schedule with the same URL and add the X-Cron-Secret header.
  • 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

Why cron-job.org?

  • No need to install node-cron or run background workers.
  • Works with serverless platforms like Vercel, Netlify, or Cloudflare.
  • Secure with your custom X-Cron-Secret.