Next.js – SSR + Client Revalidation for Authenticated Data
asked 8 months ago
1
44
I’m working on a SaaS dashboard using Next.js 14 App Router.
The dashboard needs to:
Show the user profile (from /api/me)
Show analytics stats (from /api/analytics)
Both APIs require JWT authentication stored in an HTTP-only cookie
Profile data is fine to load once on SSR, but analytics stats need to stay updated on the client every ~30s
My current approach:
The issue:
This works, but:
I’m double fetching analytics data — once during SSR (when rendering the client component shell) and once immediately on hydration.
If the user’s JWT expires while they’re browsing, SWR keeps trying to fetch, but my API responds 401 and the UI just shows an error — I want it to redirect to /login automatically on both SSR and client.
I’m not sure if this is the most performant way to handle authenticated SSR + client revalidation in App Router.
Question:
How can I fetch the initial analytics data on the server and hydrate it into the client component without double fetching?
What’s the best way to handle JWT expiry in both SSR and client contexts in the App Router?
Any performance tips to avoid unnecessary re-renders and reduce API calls in this setup?
Hey, great setup so far! Let's refine it for efficiency. I'll cover your key questions step by step.
1. Avoid Double Fetching Analytics Data
Fetch analytics on the server in your page component and pass it as a prop to the client component. This hydrates the initial data without re-fetching on the client.