Why useSession() Is undefined on First Load in Next.js When Deployed to Production (and how i fixed it)
Source: Dev.to
Problem
When I deployed my SaaS (Next.js app) to production, the first page load logged session as undefined. After refreshing (e.g., /dashboard), the session appeared correctly:
{ user: { … }, expires: "…" }
This never happened on localhost—only in production. The issue seemed related to the authentication token, but the token was fine.
Why it Happens
useSession() is asynchronous. On the initial render React mounts the component immediately, while useSession() begins fetching the session in the background. During that first render the session data isn’t available yet, so console.log(session) prints undefined and the hook’s status is "loading".
On localhost the app runs slower, giving the session request more time to resolve before you notice the log. In production the app loads faster, so the render occurs before the session is ready, exposing the undefined value.
Fixes
Check the session status on the client
import { useSession } from "next-auth/react";
const Component = () => {
const { data: session, status } = useSession();
if (status === "loading") {
return null; // or a loading spinner
}
if (!session) {
redirect("/login");
}
// render protected content
};
Guard useEffect until the session exists
import { useEffect } from "react";
useEffect(() => {
if (!session) return; // wait for session
fetchBills(session.user.id);
}, [session]);
Takeaways
- Rendering happens before asynchronous data (like
useSession) is ready, so you must handle an initialundefinedstate. - This pattern applies to any async data source: API calls, database fetches, React Query, etc.
- Production‑only bugs often stem from timing differences, not from broken logic.
Thanks for reading. If this helped you, feel free to share or connect with me.
Athashri Keny