• Stars
    star
    169
  • Rank 224,453 (Top 5 %)
  • Language
    TypeScript
  • Created over 3 years ago
  • Updated over 1 year ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Cron jobs with Github Actions for Next.js apps on Vercel▲

Note

As of February 22nd 2023 Vercel is officially offering built-in cron jobs to trigger your serverless and edge functions. Read the documentation to learn more. Keep in mind the feature is only free during its beta phase, it'll be a paid feature for general availability, which means that the GitHub Actions route will remain relevant for a completly free option.

Next.js Cron

Cron jobs with Github Actions for Next.js applications on Vercel▲

Motivation

Since the Vercel platform is event-driven, therefore not maintaining a running server, you can't really schedule calls on your API routes or Serverless functions in your Next.js application. Although there are many pre-existing services that provide scheduled cron jobs, I ultimately decided that Github Actions suits my needs the best, since it integrates nicely with any project that already lives on Github, plus it's completely free.

Get started

All Github Actions reside in the directory .github/workflows/ of your repository and are written in YAML.

.github/workflows/starter.yaml is the most basic workflow to help you get started with Actions.

Scheduled tasks

With Scheduled events you can execute tasks at specified intervals. For instance, the provided workflow .github/workflows/scheduled.yaml executes a HTTP request with curl every 60 minutes.

name: Hourly cron job
on:
  schedule:
    - cron: '*/60 * * * *'
jobs:
  cron:
    runs-on: ubuntu-latest
    steps:
      - name: Hourly cron job
        run: |
          curl --request POST \
          --url 'https://example.com/api/task' \
          --header 'Authorization: Bearer ${{ secrets.ACTION_KEY }}'

If you are having trouble writing cron schedule expressions, take a look at crontab guru.

Next.js API routes

API routes and Serverless functions provide a straightforward solution to building your API with Next.js on Vercel. Any file inside the folder pages/api is mapped to /api/* and will be treated as an API endpoint instead of a page.

If you are using serverless functions, regardless of the Runtime, you would need to put the files into the /api/ directory at your project's root.

Authorization flow

To securely trigger API routes and serverless functions with Github Actions, you need to provide an authorization key in the header of your API call, which, when executed, gets compared to a corresponding key in your Next.js application.

You can achieve this by adding Encrypted Secrets to your Github repository and passing them with the header of your HTTP request, like shown in the previous code snippet. Along with adding the key to your Github repository, you also need to access it within your Next.js application, preferably through Environment Variables.

The example pages/api/example.js implements this authorization flow.

export default function handler(req, res) {

  const { APP_KEY } = process.env;
  const { ACTION_KEY } = req.headers.authorization.split(" ")[1];

  try {
    if (ACTION_KEY === APP_KEY) {
      // Process the POST request
      res.status(200).json({ success: 'true' })
    } else {
      res.status(401)
    }
  } catch(err) {
    res.status(500)
  }
}

Use pages/api/example.ts for Typescript.

import type { NextApiRequest, NextApiResponse } from 'next'

export default function handler(req:NextApiRequest, res:NextApiResponse) {

  const { APP_KEY } = process.env;
  const { ACTION_KEY } = req.headers.authorization.split(" ")[1];

  try {
    if (ACTION_KEY === APP_KEY) {
      // Process the POST request
      res.status(200).json({ success: 'true' })
    } else {
      res.status(401)
    }
  } catch(err) {
    res.status(500)
  }
}

More Repositories

1

github-stars-download

git clone all of your starred repositories on github
Shell
5
star
2

next-magic-auth

Next.js starter with Magic email authentication
TypeScript
5
star
3

task-completion

🎵 Obsidian plugin that plays a sound everytime you complete a task
TypeScript
4
star
4

spotify-next-auth-token-rotation

NextAuth Refresh Token Rotation for Spotify OAuth
TypeScript
3
star
5

radiosource

📡 pseudorandom radio sources with astropy
Python
3
star
6

tinybrave

Brave Browser Hardening
2
star
7

whole-network-vpn

Network-wide OpenVPN with pfSense + NAT rules for latency-sensitive applications
2
star
8

artix-fde

Artix Linux Full-Disk Encryption installation guide
2
star
9

botcogs

collection of useful discord.py bot components (cogs)
Python
2
star
10

notion-sync

Sync Notion workspaces between multiple users (aka Team plan)
JavaScript
2
star
11

sprout

🌱 S3 based personal file storage service
TypeScript
1
star
12

birbs

local birds in my area
Jupyter Notebook
1
star
13

topsongs.me

Spotify playlists of your most streamed songs, likes and history (beta)
TypeScript
1
star
14

memento-mori

Your Life in Weeks (React component)
TypeScript
1
star
15

dwmblocks

📟 a modular status bar for dwm
C
1
star
16

dwm

build of dwm with custom vim bindings
C
1
star
17

markov

exploring markov chains
C++
1
star
18

next13-playground

exploring react server components
CSS
1
star
19

physics-lab

TUM Physik Praktikum (Lab course)
PostScript
1
star
20

dotfiles

🌍 home to all my files with a dot
Vim Script
1
star
21

lichess-custom-pieces

Custom pieces on Lichess.org
1
star
22

react-native-chess-clock

Chess clock with built-in match tracking (React Native)
JavaScript
1
star
23

hello-cuda

learning cuda
Jupyter Notebook
1
star
24

dmenu

my dmenu build
C
1
star
25

adventofcode

Python
1
star
26

lichess-blunders

Does the low time alarm on lichess.org make players play worse?
Python
1
star
27

euler

bad solutions to good problems
Go
1
star
28

galaxyclass

Galaxy morphology classification with Convolutional Neural Networks
Jupyter Notebook
1
star
29

templeos.online

TempleOS in a Docker container with QEMU hardware virtualization
Shell
1
star
30

cube2-quake

cube2 with quake like movement mechanics
C++
1
star