Back to roadmaps authjs Course

Retrieving User Sessions in Next.js

Auth.js supports retrieving user sessions on both the server and client. Let us look at both methods.


1. Server-Side Session Acquisition

This is the most secure method because it runs directly on the server without API network latency:

// app/dashboard/page.tsx
import React from "react";
import { auth } from "../../auth";
import { redirect } from "next/navigation";

export default async function Dashboard() {
  // Fetch active session from cookie securely
  const session = await auth();

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

  return (
    <div className="p-8">
      <h1>Welcome back, {session.user.name}!</h1>
      <p>Logged in email: {session.user.email}</p>
    </div>
  );
}

2. Client-Side Session Acquisition

To retrieve user sessions inside Client Components, wrap your page hierarchy inside a <SessionProvider> first.

A. Wrapping the Layout

// app/layout.tsx
import React from "react";
import { SessionProvider } from "next-auth/react";

export default function Layout({ children }: { children: React.ReactNode }) {
  return (
    <SessionProvider>
      <html>
        <body>{children}</body>
      </html>
    </SessionProvider>
  );
}

B. Calling useSession Hook

In any downstream React Client Component, call the useSession hook:

"use client";

import React from "react";
import { useSession } from "next-auth/react";

export default function ClientDashboard() {
  const { data: session, status } = useSession();

  if (status === "loading") {
    return <p>Syncing authentication status...</p>;
  }

  if (status === "unauthenticated" || !session) {
    return <p>Access denied. Please login.</p>;
  }

  return (
    <div>
      <p>Profile Avatar:</p>
      <img src={session.user?.image || "/fallback.png"} alt="Avatar" className="w-12 h-12 rounded-full" />
    </div>
  );
}

3. Which Strategy to Use?

  • Use Server-Side auth(): For initial page loads, SEO rendering, database queries, and server actions.
  • Use Client-Side useSession(): For dynamic client-side layouts, conditional menu updates, or client-side form logic.
Published on Last updated: