AuthUsage
requireAuth
Protect pages by redirecting unauthenticated users
requireAuth() gets the current session and redirects to sign-in if no user is authenticated. Use it when a page should only be accessible to logged-in users.
Basic Usage
import { } from "@repo/auth/server"
export default async function () {
const { } = await ()
return <>Welcome, {.name}</>
}If no session exists, the user is redirected to /sign-in.
Custom Redirect Path
const { } = await ("/login")Return Value
Returns the full session object:
const { , } = await ()
// user - The authenticated user
// session - Session metadata (id, expiresAt, etc.)Layout Protection
Protect all pages under a route group:
import { } from "@repo/auth/server"
export default async function ({
}: {
: .
}) {
await ()
return (
<>
<>Dashboard Nav</>
{}
</>
)
}All pages in app/(dashboard)/ are now protected.
Server Actions
Protect server actions:
"use server"
import { } from "@repo/auth/server"
export async function (: { : string }) {
const { } = await ()
await db.update(users)
.set({ : . })
.where(eq(users.id, .id))
return { : true }
}Role-Based Access
Build on requireAuth for role checks:
import { } from "@repo/auth/server"
import { } from "next/navigation"
export async function () {
const = await ()
if (.user.role !== "admin") {
("/dashboard")
}
return
}Use in pages:
import { } from "@/lib/auth-utils"
export default async function () {
const { } = await ()
return <>Admin Panel for {.name}</>
}When to Use
| Use Case | Function |
|---|---|
| Protected pages | requireAuth() |
| Protected layouts | requireAuth() |
| Server actions | requireAuth() |
| Conditional UI | withAuth() |
| API routes | withAuth() |