Retrieving Session States via Hooks: useUser and useAuth
Clerk provides separate hooks for Client Components and server-side utilities for Server Components. Let us master both data access layers.
1. Client-Side Hooks
Inside React Client Components (marked with "use client"), use these hooks to fetch authentication states:
A. useAuth (Session ID and State metadata)
Use useAuth when you only need status details, session tokens, or sign-out functions:
"use client";
import React from "react";
import { useAuth } from "@clerk/nextjs";
export default function SessionStatus() {
const { isLoaded, userId, sessionId, signOut } = useAuth();
if (!isLoaded) return <p>Loading authentication state...</p>;
if (!userId) return <p>Logged out</p>;
return (
<div>
<p>Logged in User ID: {userId}</p>
<button onClick={() => signOut()} className="text-red-600">Logout</button>
</div>
);
}B. useUser (Full Profile details)
Use useUser when you need details about the user profile (such as primary email, avatar image, first name, and metadata):
"use client";
import React from "react";
import { useUser } from "@clerk/nextjs";
export default function UserGreeting() {
const { isLoaded, isSignedIn, user } = useUser();
if (!isLoaded) return <p>Loading profile...</p>;
if (!isSignedIn) return <p>Please sign in</p>;
return (
<div className="flex items-center gap-4">
<img src={user.imageUrl} alt="Avatar" className="w-10 h-10 rounded-full" />
<h4>Hello, {user.firstName || "Member"}!</h4>
</div>
);
}2. Server-Side Helpers (Server Components)
Inside Next.js Server Components or API routes, you cannot use React hooks. Instead, import server helpers:
- auth(): Returns the user session metadata (contains
userIdand token fetching methods). - currentUser(): Performs a query to fetch the complete user object from the Clerk API.
// app/dashboard/page.tsx
import React from "react";
import { auth, currentUser } from "@clerk/nextjs/server";
import { redirect } from "next/navigation";
export default async function DashboardPage() {
// 1. Check user authorization
const authObject = await auth();
const userId = authObject.userId;
if (!userId) {
redirect("/sign-in");
}
// 2. Query full profile details from Clerk API
const user = await currentUser();
return (
<div className="p-8">
<h1>Dashboard Workspace</h1>
<p>Authorized User Email: {user?.emailAddresses[0].emailAddress}</p>
</div>
);
}Published on Last updated: