StartupKitstartupkit
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

app/dashboard/page.tsx
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:

app/(dashboard)/layout.tsx
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:

app/actions/profile.ts
"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:

lib/auth-utils.ts
import {  } from "@repo/auth/server"
import {  } from "next/navigation"

export async function () {
  const  = await ()

  if (.user.role !== "admin") {
    ("/dashboard")
  }

  return 
}

Use in pages:

app/admin/page.tsx
import {  } from "@/lib/auth-utils"

export default async function () {
  const {  } = await ()

  return <>Admin Panel for {.name}</>
}

When to Use

Use CaseFunction
Protected pagesrequireAuth()
Protected layoutsrequireAuth()
Server actionsrequireAuth()
Conditional UIwithAuth()
API routeswithAuth()

Next Steps

  • withAuth - Get session without redirecting
  • useAuth - Client-side auth hook

On this page