Private Page
Sometimes you don't want a user to access a page or a specific route specially if they are not logged in to do so follow the instructions below
Server components
The example below will show you how to check if the user is logged in on a server component
app/dashboard/layout.tsx
import { validateRequest } from "lib/auth";
import { redirect } from "next/navigation";
import { FC, PropsWithChildren } from "react";
import LayoutControl from "./_layout/layout-control";
const DashboardLayout: FC<PropsWithChildren> = async ({ children }) => {
const { session, user } = await validateRequest();
if (!session || user.role !== "ADMIN") redirect("/");
return <div>{children}</div>;
};
export default DashboardLayout;
Client components
In client components we can use the application state to see if the user is logged in and if not redirect them back somewhere else
app/example_page/page.tsx
"use client";
import { FC, PropsWithChildren, useEffect } from "react";
import { useRouter } from "next/navigation";
import { useAppState } from "store";
const ExamplePage: FC<PropsWithChildren> = ({ children }) => {
const router = useRouter();
const user = useAppState((state) => state.user);
useEffect(() => {
if (!user) router.push("/");
}, [user, router]);
return user ? <div>{children}</div> : null;
};
export default ExamplePage;