Skip to main content

Command Palette

Search for a command to run...

Why useSession() Is undefined on First Load in Next.js When Deployed to Production (and how i fixed it)

Published
2 min read
A

As a passionate Third-year Computer Science student, I specialize in creating engaging web experiences using modern technologies. My focus is on building accessible, and performant applications.

When i Deployed my Saas (next.js app) in production i noticed something strange. On the first load my console showed session undefined but when i refreshed the page ie /dashboard everything worked perfectly.

Even More Confusing that this never happened on localhost, only happened in production. At first i thought my auth token is broken. Turns out it wasn’t

This blog explains what was actually happening, why this bug appears only in production, and how to fix it properly.

The Setup i was using Next.js (App Router) , Next Auth , useSession() on the client , Protected dashboard page . A every common

The problem

On initial page load:

const { data: session } = useSession();

console.log(session);

output -

undefined

But after refresh:

{ user: {...}, expires: "..." }

So the big question was:

Why is the session undefined on first load but works after refresh?

The Real Reason

useSession() is ASYNC

this is the KEY which i misunderstood first

So when the page renders React renders components immediately. useSession() starts fetching the session

that session is not available yet hence that console.log(session) shows

session = undefined status = "loading"

Why this does not happens in localhost

EnvironmentWhat happens
LocalhostSlower → session resolves early
ProductionFaster → render happens first

The Correct Fix (Client-Side)

1. Always check status

const { data: session, status } = useSession();

if (status === "loading") { return null;

if (!session) { redirect("/login"); }

2. Guard useEffect

useEffect(() => { if (!session) return;

fetchBills(session.user.id); }, [session]);

The Big Lesson I Learned

Rendering happens before async data is ready. Always assume undefined once.

This applies not just to useSession(), but to:

  • API calls

  • Database fetches

  • React Query

  • Any async data

“Production bugs don’t mean you’re bad — they mean you’re learning real-world development.”

Thanks for reading!!

If this helped you, feel free to share or connect with me.

Athashri Keny!