How to run a server side function on a loop with NextJS?

Viewed 23

In my NextJS project, there is a setInterval function in airdropLoop.ts that I would like to automatically run after next dev or next start is called. Is this possible?

Edit: My NextJS project is for public APIs only, so there are no client pages / ability to run useEffect()/getServerSideProps(). The tl;dr is that one of my public endpoints simply adds items to a DB. The airdropLoop.ts should be running in the background every minute and checking if new items have been added. I want it to happen on a loop because it will be more efficient to wait for the DB to fill up a bit than running a function anytime something is added to the DB. I would rather not use a cron job.

1 Answers

You can use GetServerSideProps to run the function on the server before the page is rendered. So you can run it when the user loads your homepage. You can also use GetInitialProps on the _app.js page to run some server side code this will ensure that it is always run but is not recommended.

You can also achieve this by making a server route in the /api directory and utilizing reacts useEffect to make a request to this route.

Related