Next.js Discord

Discord Forum

Schedule a server function to run after set amount of time

Answered
Sun bear posted this in #help-forum
Open in Discord
Sun bearOP
I have a confirmation email system where I generate a 6 digit code on the server, store it in verify_email_code table in db and email user the code.

The verify_email_code table has created_at column which is used to check if the code has expired, but a more elegant approach would be to just delete the entry from the database after a set amount of time. This way the database will not need to store unnecessary data.

How do I schedule a job using next.js server actions. Would a setTimeout do the job or is that not possible?

"use server"

const EXPIRE_TIME = 1000 * 60 * 10 // 10 minutes (ms)

async function scheduleExpireCode(email: string, code: number) {
  setTimeout(() => {
    await removeCodeFromDb(email, code)
  }, EXPIRE_TIME)
}

async function verifyUser(email) {
  const code = await generateCode()
  await insertCodeToDb(email, code)
  await mailUserACode(email, code)

  await scheduleExpireCode(email, code)
}
Answered by Arinji
NextJS itself has 0 support for cron job type situations, setTimeout wont work in this case. There are 2 things you can do

1) If you use vercel, you can make your server action into an api route and use the vercel cron jobs to call the api route :D
2)If you dont use vercel, use any backend framework like express or hono, and use node-cron to call the api route. You will need an external server for this however.
View full answer

14 Replies

NextJS itself has 0 support for cron job type situations, setTimeout wont work in this case. There are 2 things you can do

1) If you use vercel, you can make your server action into an api route and use the vercel cron jobs to call the api route :D
2)If you dont use vercel, use any backend framework like express or hono, and use node-cron to call the api route. You will need an external server for this however.
Answer
@Sun bear
Sun bearOP
well I don't have a backend and I self-host next via docker...
so my only solution is to make an express server for a cron job lol
i do that as well
so its fine
i dockerize a bun hono project, with cron jobs
sounds good?
Sun bearOP
wait what is hono?
yes
just a lightweight express
Sun bearOP
ohh thank you I will look into it
Sure, mark a solution if it helped :D