Next.js Discord

Discord Forum

can i run serverside background tasks

Unanswered
Egyptian Mau posted this in #help-forum
Open in Discord
Avatar
Egyptian MauOP
so i basically want to have a page displaying what i'm listening to on spotify, and for that i thought i'd have an API route on MY serverside that the frontend would call to receive the latest spotify data, and the code behind that API route would be a background task polling the spotify API every now and then, and just forwarding the data clientside whenever a user requests it

this is so that i don't have to make requests to spotify directly from the frontend, because i'm worried that can be abused, and i'm wondering how i can implement the background task that constantly fetches new data in next

25 Replies

Avatar
Blanc de Hotot
where you hosting your app
@Egyptian Mau if you're hosting on vercel all the solutions are super ugly
especially if that long runnign background task takes longer than 15 minutes
is it a relatively quick task?
but this is probably what you want to look at
and you tell it to run a function every minute
just be aware of the potential costs
Avatar
Egyptian MauOP
locally/on vps
yeah just sends a request to spotify
but i need to keep doing it very frequently (like minimum every 15sec)
Avatar
Blanc de Hotot
hrm, the issue is every time you do that you're invoking a new lambda
how quickly does the request run?
and how much data is it pulling from spotify?
and is it doing a lot of transofmring?
oh well
that's much easier
so you set up a cronjob
write a simple script that can get run, in what ever language you want
type crontab -e
you'll get a window up which you edit in terminal
and you basically define what the timing is and then point it to your script
and it'll automatically call that script at those time intervals
Avatar
Blanc de Hotot
https://phoenixnap.com/kb/set-up-cron-job-linux
https://crontab.guru/

but i don't think cron can do under 1 min intervals which out a bit of dirtiness
Avatar
Blanc de Hotot
crontab -e
0/1* * * * /usr/local/bin/node /home/some-script.js