Securing Pages
Client-Side Protection
To protect client-side routes, use getCurrentUser()
to check if the user is authenticated. If not, redirect them to the login page using the signIn()
function:
import { signIn, config } from "@/config";
import { useSession } from "@/lib/auth/client";
export default function DashboardPage() {
const { data: session, isPending } = useSession();
if (isPending) return <div>Loading...</div>;
if (!session) return <div>Not authenticated</div>;
return (
<>
<h1>Welcome to your Dashboard</h1>
{/* Your dashboard content */}
</>
);
}
Server-Side Protection
For server-side route protection, use the auth()
function provided by Next Auth:
import { auth } from "@/lib/auth";
import { signIn, config } from "@/config";
export default async function SettingsPage() {
const session = await auth.api.getSession({
headers: await headers(),
});
return (
<div>
<h1>Settings</h1>
{/* Your settings content */}
</div>
);
}
Securing API Routes
To protect API routes, use the auth()
function in your route handlers:
import { auth } from "@/lib/auth";
import { NextRequest, NextResponse } from "next/server";
import { HttpStatusCode } from "axios";
export async function GET(request: NextRequest) {
const session = await auth.api.getSession({
headers: await headers(),
});
if (!session)
return NextResponse.json(
{ message: "Not authenticated" },
{ status: HttpStatusCode.Unauthorized }
);
// Your protected API logic here
return NextResponse.json({ message: "This is a protected API route" });
}