Nextjs Dynamic server usage

By using headers in a function to get the userid on the server side, my page isn’t rendered statically anymore. Is there an actual clean server side logic to get the user Id?
12 Replies
Luis
LuisOP7d ago
No description
daveycodez
daveycodez6d ago
Getting a user ID in a server side render will never be static, by definition
Luis
LuisOP6d ago
Yes that’s what I also though but in clerk it was
daveycodez
daveycodez6d ago
It's just not possible
Luis
LuisOP6d ago
Or am I wrong
daveycodez
daveycodez6d ago
If you have dynamic data its not static
Luis
LuisOP6d ago
How can I though then suppress all my build warnings When I build my page
daveycodez
daveycodez6d ago
Clerk likely used some sort of React context provider which is client side session if it was "static" TBH it doesn't make a ton of sense to get the user ID in an SSR render. You need to use the useSession hook on the client anyways so that it stays up to date You only want user ID server side if you are doing mutations or api requests
Luis
LuisOP6d ago
Yes and that’s what I am doing
daveycodez
daveycodez6d ago
If you are using useSession hook client side and also fetching session on the render it leads to a double fetch Your server will query the data on the render and then your client will send a request to your API which will query the db again or use cookie cache, but still its duplicated Your page should just use
const { data: sessionData } = useSession()
const userId = sessionData?.user.id
const { data: sessionData } = useSession()
const userId = sessionData?.user.id
Then you can have a static page, very fast and cheaper if hosting on a service like Vercel Anywhere you are using your userId on a React component you want to have "use client" directive
Luis
LuisOP6d ago
Okay thanks, yes I am self-hosting though. So generally speaking its always smart to static render all content which is not connected to an user. (On protcted pages). And then on client side, we fetch via api / trpc calls the user information?
daveycodez
daveycodez6d ago
Yea dynamic information is good to be fetched from client. But for sessions you definitely want to use the useSession hook or my better-auth-tanstack package Which has TS query hooks for Better Auth

Did you find this page helpful?