StartupKitstartupkit
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

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

app/api/user/route.ts
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:

app/pricing/page.tsx
import {  } from "@repo/auth/server"

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

  return (
    <>
      <>Pricing</>
      { ? (
        <CurrentPlanDetails ={.id} />
      ) : (
        <PublicPricingTable />
      )}
    </>
  )
}

Root Layout

Pass user to client providers:

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

middleware.ts
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 CaseFunction
Conditional UIwithAuth()
API routeswithAuth()
Root layoutwithAuth()
Protected pagesrequireAuth()
Server actionsrequireAuth()

Next Steps

On this page