Performance: Why authentication matters
Authentication affects initial page load speed and interaction responsiveness by controlling access to content and resources.
Jump into concepts and practice - no test required
import { cookies } from 'next/headers'; export default async function Page() { const cookieStore = cookies(); const token = cookieStore.get('authToken')?.value; if (!token) { return <div>Please login</div>; } const response = await fetch('http://localhost:3000/api/user', { headers: { Authorization: `Bearer ${token}`, }, }); const user = await response.json(); return <div>Welcome {user.name}</div>; }
'use client'; import { useState, useEffect } from 'react'; export default function Page() { const [user, setUser] = useState(null); useEffect(() => { fetch('/api/user').then(res => res.json()).then(setUser); }, []); if (!user) { return <div>Please login</div>; } return <div>Welcome {user.name}</div>; }
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Client-side auth fetch | More DOM nodes due to delayed rendering | Multiple reflows as content updates | Higher paint cost due to delayed content | [X] Bad |
| Server-side auth check | Minimal DOM nodes initially | Single reflow on initial render | Lower paint cost with immediate content | [OK] Good |
import to load libraries.import NextAuth from 'next-auth'; with exact casing and syntax.import { useSession } from 'next-auth/react';
export default function Profile() {
const { data: session } = useSession();
if (!session) {
return <p>Please sign in to view your profile.</p>;
}
return <p>Welcome, {session.user.name}!</p>;
}session will be null or undefined.<p>Please sign in to view your profile.</p> when !session is true.import { useSession } from 'next-auth/react';
export default function Dashboard() {
const session = useSession();
if (!session) {
return <p>Access denied.</p>;
}
return <p>Dashboard content</p>;
}data property containing the session info.const { data: session } = useSession(); to get the session data.getServerSideProps allows checking the session before rendering the page.