TutorialsPrivate page

Once user authentification is set, you can start to build private routes like a user dashboard, account, etc.

The usePrivate custom hook opens the login page if user isn't auth. And it also redirects the user to the right page after login (see callbackUrl in config.js)

If you want to make protected API calls, follow this tutorial.

dashboard.js

1
2import { useState } from "react";
3import { signOut } from "next-auth/react";
4import apiClient from "@/libs/api";
5import { usePrivate } from "@/hooks/usePrivate";
6import TagSEO from "@/components/TagSEO";
7
8export default function Dashboard() {
9  // Custom hook to make private pages easier to deal with (see /hooks folder)
10  const [session, status] = usePrivate({});
11  const [isLoading, setIsLoading] = useState(false);
12
13  // Show a loader when the session is loading. Not needed but recommended if you show user data like email/name
14  if (status === "loading") {
15    return <p>Loading...</p>;
16  }
17
18  return (
19    <>
20      <main
21        className="min-h-screen p-8 pb-24"
22      >
23        <section className="max-w-xl mx-auto space-y-8">
24          <h1 className="text-3xl md:text-4xl font-extrabold">
25            Your Food Recipes
26          </h1>
27
28          <p className="text-lg leading-relaxed text-base-content/80">
29            {status === "authenticated"
30              ? `Welcome ${session?.user?.name}`
31              : "You are not logged in"}
32            <br />
33            {session?.user?.email
34              ? `Your email is ${session?.user?.email}`
35              : ""}
36          </p>
37
38          <button
39              className="btn btn-ghost"
40              onClick={() => signOut({ callbackUrl: "/" })}
41            >
42              Logout
43            </button>
44        </section>
45      </main>
46    </>
47  );
48}