Securing Pages

Client-Side Protection

To protect client-side routes, use getCurrentUser() to check if the user is authenticated. If not, redirect them to the login page using the signIn() function:

import { signIn, config } from "@/config";
import { getCurrentUser } from "@/lib/session";

export default function DashboardPage() {
  const user = await getCurrentUser() ?? null;
  if (!user) return signIn(undefined, { callbackUrl: config.auth.signInRedirectUrl })
  return (
    <>
      <h1>Welcome to your Dashboard</h1>
      {/* Your dashboard content */}
    </>
  )
}

Server-Side Protection

For server-side route protection, use the auth() function provided by Next Auth:

import { auth } from "@/auth"
import { signIn, config } from "@/config";

export default async function SettingsPage() {
  const session = await auth()
  if (!session) return signIn(undefined, { callbackUrl: config.auth.signInRedirectUrl })

  return (
    <div>
      <h1>Settings</h1>
      {/* Your settings content */}
    </div>
  )
}

Securing API Routes

To protect API routes, use the auth() function in your route handlers:

import { auth } from "@/auth"
import { NextRequest, NextResponse } from "next/server"
import { HttpStatusCode } from 'axios';

export async function GET(request: NextRequest) {
  const session = await auth()

   if (!session) return NextResponse.json({ message: "Not authenticated" }, { status: HttpStatusCode.Unauthorized });

  // Your protected API logic here
  return NextResponse.json({ message: "This is a protected API route" })
}