NextJs Cron Jobs
Answered
Western harvester ant posted this in #help-forum
Western harvester antOP
Hello guys, hope you are doing well, I am currently making an auction type application using NextJs and payload with mongoDB, I need to expire auctions when their end time is past, for that i am using a cron job that runs every 1 or 5 minutes to update the auction statuses, however after looking at some reddits threads online people are saying to not use cron jobs with NextJs or make the cronjob a public API and using service like vercel or github to call it, rn i am using it in the payload.config.ts with node-cron to schedule it every 5 mins, however that gives a webpack error since it runs both on server and client side. GPT is suggesting me to put it into server.ts file instead, however I dont know if that will be optimal or bad practice, could you guys please suggest some possible solutions or is simply calling the cron job in nextJs application in server.ts, etc.. safe or not? (I am really sorry if its a stupid question or i wasted your time, tho tyvm for taking the time to read this and trying too help ❤️ ).
Answered by Asian black bear
If you're hosting your app serverless you won't be able to use cronjob code within Next itself. If you self-host, it is technically possible but still not the way to go. As others have suggested, create a route handler that you ping once in a while like a webhook (using a token to prevent malicious actors from spamming it) or setup a local cronjob using crontab.
6 Replies
Western harvester antOP
import cron from 'node-cron'
dotenv.config({
path: path.resolve(__dirname, '../.env'),
})
export default buildConfig({
serverURL: process.env.NEXT_PUBLIC_SERVER_URL || '',
collections: [Users, Products, Media, ProductFiles, Orders, Memberships],
routes: {
admin: '/sell',
},
admin: {
user: 'users',
bundler: webpackBundler(),
meta: {
titleSuffix: '- CircularXChange',
favicon: '/favicon.ico',
ogImage: '/thumbnail.jpg',
},
},
rateLimit: {
max: 2000,
},
editor: slateEditor({}),
db: mongooseAdapter({
url: process.env.MONGODB_URL!,
}),
typescript: {
outputFile: path.resolve(__dirname, 'payload-types.ts'),
},
onInit: async (payload) => {
const existing = await payload.find({
collection: 'memberships',
where: { name: { equals: 'Free' } },
});
if (!existing.docs.length) {
await payload.create({
collection: 'memberships',
data: {
name: 'Free',
monthlyBids: 5,
monthlyPosts: 5,
price: 0,
features: [
{ feature: 'Limited access to features' },
{ feature: 'Limited support' },
],
stripePriceId: 'free',
},
});
}
cron.schedule('* * * * *', async () => {
console.log('Running cron job to close auctions...')
try {
closeAuctions(payload)
} catch (error) {
console.error('Error in auction cron job:', error)
}
})
},
})
rn i am calling it like this in payload.config.ts, however it gives an error when it initially compiles
Asian black bear
If you're hosting your app serverless you won't be able to use cronjob code within Next itself. If you self-host, it is technically possible but still not the way to go. As others have suggested, create a route handler that you ping once in a while like a webhook (using a token to prevent malicious actors from spamming it) or setup a local cronjob using crontab.
Answer
@Asian black bear If you're hosting your app serverless you won't be able to use cronjob code within Next itself. If you self-host, it is technically possible but still not the way to go. As others have suggested, create a route handler that you ping once in a while like a webhook (using a token to prevent malicious actors from spamming it) or setup a local cronjob using crontab.
Western harvester antOP
ohhk sounds good, will look more into crontab and possibly setting up the route too ping once in a while, btw do you know what service i can use too ping the route like every 5minutes or so? i am not using vercel too deploy/host the code so i can't use that.
Asian black bear
If you're self-hosting you don't need any service. A local cronjob will work fine.
Everything else is third-party, partially paid or not 100% reliable.
@Asian black bear If you're self-hosting you don't need any service. A local cronjob will work fine.
Western harvester antOP
ohh right, thank you very much for the help.