Next.js Discord

Discord Forum

unauthorized() does not seem to work properly in all situations

Unanswered
Tyler posted this in #help-forum
Open in Discord
I have a layout that is checking for the role in the user's session. If there is no 'admin' role, I call unauthorized() from next/navigation. Unfortunately, the user is not being redirected to my unauthorized() page, and I see 200 response codes in the server...

I set up an app/testing/page.tsx and app/testing/layout.tsx and just having unauthorized() seems to work fine there...

This is my src/app/(dashboard)/layout.tsx file which just checks the session for approved role (which my user does have):
export default async function Layout({
  children,
}: {
  children: React.ReactNode;
}) {
  console.log("Layout rendered from dash");
  const session = await auth.api.getSession({
    headers: await headers(),
  });

  if (!session) {
    unauthorized();
  }

  const { user } = session;

  if (!user.role.split(",").includes("approved")) {
    console.log("Unauthorized access attempt by user:", user.email);
    unauthorized();
  }

  return (
    <div className="w-full">
      <AdminBar />
      <NavBar />
      <div className="container mx-auto py-4">{children}</div>
    </div>
  );
}


And then this is my src/app/(dashboard)/admin/layout.tsx:
import { auth } from "@/server/auth";
import { headers } from "next/headers";
import { unauthorized } from "next/navigation";

export default async function Layout({
  children,
}: {
  children: React.ReactNode;
}) {
  const session = await auth.api.getSession({
    headers: await headers(),
  });

  if (!session) {
    unauthorized();
  }

  const { user } = session;

  console.log("usersdf", user.role.split(",").includes("admin"));

  if (!user.role.split(",").includes("admin")) {
    console.log("Unauthorized access attempt by user:", user.email);
    unauthorized();
  }

  return <>{children}</>;
}


My console.log in the admin/layout.tsx DOES fire, so authorized() should be running, but the user sees the /admin page and a 200 response...

3 Replies

if I put unauthorized() at the top of my src/app/(dashboard)/layout.tsx file, it does return unauthorized and show my page, as expected:

export default async function Layout({
  children,
}: {
  children: React.ReactNode;
}) {
  unauthorized();


but inside src/app/(dashbopard)/admin/layout.tsx or the page.tsx file, it doesn't seem to do anything.
Can unauthorized not be used in nested layouts?
It looks like I HAVE to have an unauthorized.tsx file in my admin/ page?