Private Pages

Pages like Dashboard need authentication checks, learn how to protect them.

Pages

To protect your app pages, simply take advantage of the NextAuth Session Hook:

import { useSession } from "next-auth/react";

export default function ExamplePage() {
  const session = useSession();
  
  if (session.status === "unauthenticated") router.push("/");
  
return (
    <section>
      {session.status === "loading" && <div>Please wait</div>}
      {session.status === "unauthenticated" && <div>Please log in</div>}
      {session.status === "authenticated" && <div>Hello World</div>}
    </section>
  )
}

API

You should always protect your backend calls to avoid malicious behavior, it's similar to pages thanks to NextAuth:

import { getServerSession } from "next-auth/next";
import { authOptions } from "../auth/[...nextauth]/options";

export async function POST(request: Request) {
  const session = await getServerSession(authOptions);
  if (session?.user.role !== "admin") {
    return new Response("Unauthorized", {
      status: 401,
      statusText: "Unauthorized",
    });
  }
  ...
}

Last updated