Next.js Discord

Discord Forum

How to efficiently perform a one-time Supabase request on site load in Next.js?

Answered
Scottish Fold posted this in #help-forum
Open in Discord
Avatar
Scottish FoldOP
Hi! Could you please give me some advice on how to implement this? At work, we have an old Next.js project with significant architectural issues and a lot of messy code. I need to ensure that upon the first site load, a single request is made to the Supabase database. Based on the database response, two keys should be removed from the cookies. Could you suggest the best place to implement this logic? I’ve currently added it to the middleware, but this solution doesn’t work because the request is triggered on every server call. I need it to run only once — either on the initial page load or when the user refreshes the page.
Answered by Alfonsus Ardani
Two strategies that i can think out of my head:
1. Use client side useState in root layout so that you can track if it has been run once and have its state persisted in between navigations (due to how soft navigation works). See: https://nextjs-forum.com/post/1315266857728610335#message-1315289791994134538

2. If you want to use server-side data fetching, you can read the sec-fetch-dest header if its equal to documents which means a hard page reload
View full answer

7 Replies

Avatar
.
Answer
Avatar
Scottish FoldOP
I’m really annoyed by how difficult it is to manage cookies in Next.js. The document object isn’t always accessible, and removing cookies via API routes doesn’t always work either...
Avatar
removing cookies via api routes... should be relatively easy, no? how did you do it?
cookies aren't meant to be accessed in the client-side js. so i can only understand why its a bit unintuitive to access it via the document object
Avatar
Scottish FoldOP
It looks like the method using sec-fetch-dest worked exactly as I needed. Thank you so much:thank_you:
Avatar
wow nice