Marcel Dz
Marcel Dz

Reputation: 2714

Next.js how to work with sheduled functions?

I want to create a scheduled function which will reset a prize on my website every night. In the function I need to call my database with some sensible data. Im wondering where is the perfect place to write the function and make it work? I just noticed that _app.js would probably make it? It seems like this page provides client and serverside so I can write a scheduled function calling my prize reset function giving sensible data to do that and Im fine? If I console.log this im getting the variable on serverside only. So everything looks good to me. Does someone have experience on this and can confirm this and/or show a better solution?

import '../styles/globals.css'

console.log('_app.js:' + process.env.JWT_SECRET)

function MyApp({ Component, pageProps }) {
  return <Component {...pageProps} />
}

export default MyApp

Upvotes: 0

Views: 623

Answers (1)

Ivan V.
Ivan V.

Reputation: 8101

What you need is a cron job, but you can't do it with Next.js API functions if you are not using a custom server.

Next.js API functions are serverless which means that there is no running server and functions are triggered as needed. To trigger the functions at a specific time, you would need to hit your API point from an external source.

For example, using github actions, you could hit your API endpoint, every 15 minutes. Make sure you have authorization check on your endpoint, and pass that authorization via headers.

name: 15-minute-cron
on:
  schedule:
    - cron: '*/15 * * * *'
jobs:
  cron:
    runs-on: ubuntu-latest
    steps:
      - name: Call our API route
        run: |
          curl --request POST \
          --url 'https://yoursite.com/api/cron' \
          --header 'Authorization: Bearer ${{ secrets.API_SECRET_KEY }}'

More information in the Vercel Docs

Upvotes: 2

Related Questions