Loading...
Loading...
> Create pages that require authentication to access.
Middleware-based route protection with automatic redirects, role-based access control, and conditional UI rendering based on authentication state.
Create your page under a protected directory
1// src/app/(dashboard)/dashboard/my-feature/page.tsx23import { auth } from "@/lib/auth";45export default async function MyFeaturePage() {6 const session = await auth();78 // Session is guaranteed to exist (middleware handles redirect)9 const user = session!.user;1011 return (12 <div>13 <h1>Welcome, {user.name}!</h1>14 <p>Email: {user.email}</p>15 </div>16 );17}
Update middleware to protect additional routes
1// src/middleware.ts23// Find this section and add your routes:4const isOnDashboard = pathnameWithoutLocale.startsWith('/dashboard');5const isOnAdmin = pathnameWithoutLocale.startsWith('/admin');6const isOnBilling = pathnameWithoutLocale.startsWith('/billing');7const isOnSettings = pathnameWithoutLocale.startsWith('/settings');8const isOnMyFeature = pathnameWithoutLocale.startsWith('/my-feature'); // Add this910const isProtectedRoute = isOnDashboard || isOnAdmin || isOnBilling || isOnSettings || isOnMyFeature;
Restrict pages by user role
1// src/app/(dashboard)/admin/page.tsx23import { auth } from "@/lib/auth";4import { redirect } from "next/navigation";56export default async function AdminPage() {7 const session = await auth();89 // Check for admin role10 if (session?.user?.role !== 'ADMIN' && session?.user?.role !== 'SUPER_ADMIN') {11 redirect('/dashboard');12 }1314 return (15 <div>16 <h1>Admin Dashboard</h1>17 {/* Admin-only content */}18 </div>19 );20}
Use the session hook for client components
1"use client";23import { useSession } from "next-auth/react";4import { redirect } from "next/navigation";56export function ProtectedClientComponent() {7 const { data: session, status } = useSession();89 if (status === "loading") {10 return <div>Loading...</div>;11 }1213 if (!session) {14 redirect("/");15 }1617 return (18 <div>19 <p>Welcome, {session.user?.name}!</p>20 </div>21 );22}
Show different content based on authentication state
1"use client";23import { useSession } from "next-auth/react";4import Link from "next/link";56export function NavBar() {7 const { data: session } = useSession();89 return (10 <nav>11 <Link href="/">Home</Link>1213 {session ? (14 <>15 <Link href="/dashboard">Dashboard</Link>16 <Link href="/profile">Profile</Link>17 </>18 ) : (19 <>20 <Link href="/auth/signin">Sign In</Link>21 <Link href="/auth/signup">Sign Up</Link>22 </>23 )}24 </nav>25 );26}
Fabrk protects these routes via middleware. Unauthenticated users are automatically redirected to the home page:
/dashboard/*/admin/*/billing/*/settings/*USER - Default role for all usersADMIN - Administrative accessSUPER ADMIN - Full system access[ERROR]: Infinite redirect loop
Solution: Check middleware.ts protected route configuration
// Ensure login page is NOT in protected routes
const isOnAuth = pathnameWithoutLocale.startsWith('/auth');
// Don't protect auth routes
if (isOnAuth) {
return NextResponse.next();
}[ERROR]: Page not redirecting to login
Solution: Verify auth() is imported and middleware is configured
// In your protected page
import { auth } from "@/lib/auth";
export default async function Page() {
const session = await auth();
if (!session) {
redirect("/"); // Manual redirect if needed
}
}[ERROR]: Session is undefined in Server Component
Solution: Ensure page is Server Component (no "use client")
// Server Component (correct)
import { auth } from "@/lib/auth";
export default async function Page() {
const session = await auth(); // Works
}
// Client Component (wrong for auth())
"use client";
import { auth } from "@/lib/auth"; // Error!
// Use useSession() hook instead[ERROR]: User can access admin page without admin role
Solution: Add role check in page component
const session = await auth();
// Middleware only checks if logged in
// Page must check specific role
if (session?.user?.role !== 'ADMIN') {
redirect('/dashboard');
}