1

Hello I need to run a function on first start of the server, basically I want to put some constant data in the database. Yes, I could use just a in memory constant for this but I'd rather have it in my database because I am planning on using that data on some of my other servers in the future. The problem is, I am using NextJS and I want to host on the Vercel platform so I don't want to use a custom server.js file.

Is there any way to run a function only once when the server first starts in NextJS/NodeJS?

1 Answers1

0

So the Vercel platform is serverless: https://vercel.com/docs/serverless-functions/introduction.

As it states in the documentation you can create a serverless function like so:

module.exports = (req, res) => {
  res.send("Hello World");
}

If you wish to run a function after the build is done you can look at this answer:

Next.js run function/script when starting app

You could also use getServerSideProps to run code before the page renders (on the server side) if that is what you mean with "app start".

https://nextjs.org/docs/basic-features/data-fetching#getserversideprops-server-side-rendering

Ismailp
  • 2,333
  • 4
  • 37
  • 66
  • When using the solution from the linked question, the function runs twice every time a hot reload happens.. Although I'm guessing in production it should only run once ever(well, two times for some reason)? – randomprogramming May 26 '21 at 13:36
  • @randomprogramming what do you mean with "app start"? The linked question runs after a build is done. If you wish to run some function on request you could do so in the getServerSideProps. I updated my answer. – Ismailp May 26 '21 at 13:38
  • I meant on app build, but I am wondering how will this solution work in production env? Since right now the function runs every time I open a new page.. Will the function in production trigger every time any new user opens the page? – randomprogramming May 26 '21 at 13:42
  • 1
    No, the build is done once. You can see it in the Vercel log as well when the app is deploying on their platform. @randomprogramming – Ismailp May 26 '21 at 13:48
  • Okay that's what I was wondering, thanks! – randomprogramming May 26 '21 at 13:49
  • No worries, happy coding :) – Ismailp May 26 '21 at 13:49