AuthUsage
withAuth
Get the current session without redirecting
withAuth() returns the current session if one exists, or null values if not. Use it for conditional rendering or API routes where you need to handle unauthenticated states yourself.
Basic Usage
import { } from "@repo/auth/server"
export default async function () {
const { } = await ()
return (
<>
{ ? (
<>Welcome back, {.name}</>
) : (
< ="/sign-in">Sign In</>
)}
</>
)
}Return Value
Always returns an object with user and session:
const { , } = await ()
// Authenticated: { user: User, session: Session }
// Not authenticated: { user: null, session: null }API Routes
Protect API routes and return proper HTTP status:
import { } from "@repo/auth/server"
import { } from "next/server"
export async function () {
const { } = await ()
if (!) {
return .(
{ : "Unauthorized" },
{ : 401 }
)
}
return .({ })
}Conditional Content
Show different content based on auth state:
import { } from "@repo/auth/server"
export default async function () {
const { } = await ()
return (
<>
<>Pricing</>
{ ? (
<CurrentPlanDetails ={.id} />
) : (
<PublicPricingTable />
)}
</>
)
}Root Layout
Pass user to client providers:
import { } from "@repo/auth/server"
import { } from "./providers"
export default async function ({
}: {
: .
}) {
const { } = await ()
return (
<>
<>
< ={}>
{}
</>
</>
</>
)
}Client Components
For client-side auth checks, use the useAuth hook instead:
"use client"
import { } from "@repo/auth"
export function () {
const { , , } = ()
if () return <Skeleton />
return ? (
<>{?.name}</>
) : (
< ="/sign-in">Sign In</>
)
}Middleware
For edge-based checks, use Next.js middleware:
import { } from "next/server"
import type { } from "next/server"
export function (: ) {
const = ..("better-auth.session_token")
if (...("/dashboard")) {
if (!) {
return .(new ("/sign-in", .))
}
}
return .()
}
export const = {
: ["/dashboard/:path*"]
}When to Use
| Use Case | Function |
|---|---|
| Conditional UI | withAuth() |
| API routes | withAuth() |
| Root layout | withAuth() |
| Protected pages | requireAuth() |
| Server actions | requireAuth() |
Next Steps
- requireAuth - Redirect unauthenticated users
- useAuth - Client-side auth hook