Next.js Discord

Discord Forum

nextjs make server side code run on every page load

Unanswered
Dusky Warbler posted this in #help-forum
Open in Discord
Avatar
Dusky WarblerOP
Hey. I am currently using the following code to obtain the referrer to my website. However, doing it this way means that I have to add this code onto every single page that I have. What I am looking for is to place this into once place in my code so that it will run on all websites, is this at all possible?

I tried putting it inside of my _app.tsx file, but because this is not a page it doesn't run getServerSideProps.

export async function getServerSideProps(context) {
  const referer = context.req.headers.referer;
  console.log(referer);

  return {
    props: {
      referer,
    },
  };
}

10 Replies

Avatar
Asian black bear
One solution if you want the client to have it might be using middleware to inject request data into the document body, a cookie, or maybe even a query string
Also, if this is a new project, it sounds like you would be much more comfortable with using the /app, where this would be trivially easy.
Avatar
Dusky WarblerOP
Okay thank you 🙂
Avatar
Dusky WarblerOP
ahh dam! it looks like you cannot run prisma in middleware functions?
Image
that foils my plans 😛
Avatar
Asian black bear
Yah the edge runtime is a little exotic for libraries who don't support it! Is there a reason you can not use the app dir? It reallly would solve your problems I think!
Avatar
Dusky WarblerOP
Unfortunetly I have written my entire site using nextjs pages. I'm not entirely sure how much work it is to rewrite to using app directory. But I don't have that much time to rewrite anything at the moment. I was just hoping to add some analytics for my site to see which pages/endpoints are being used the most, etc... (and maybe add some global rate limit functions to stop people from abusing it)

I'll have a look into app dir once I get some time, thank you for the responses 🙂
Avatar
Asian black bear
Switching is relatively trivial, unless you are doing something that the app dir doesn't support well, in which case it is relatively impossible!

Almost always I send analytics data from the client side. What you seem to be doing would add a hard dependency on every pageview running a server-side part on every view. For analytics, there is no reason to exfiltrate the Referrer in header to the client side because you can just use document.referrer.
A good platform like Google Analytics, or its other competitors will worry about rate limits and spam/fake calls for you
Avatar
Dusky WarblerOP
brilliant, thank you 🙂