Next.js Discord

Discord Forum

How to reflect auth state in Navbar in NextJS 13?

Unanswered
Spectacled bear posted this in #help-forum
Open in Discord
Avatar
Spectacled bearOP
I am using supabase ssr and have set up authentication, which seems to be working fine.

Login logs in, sets cookies, etc. Logout removes cookies, no session, etc.

But I don't really understand how I can reflect the UI state in the Navbar the best way.

At the moment I opted to go client side with a component, get the current session with await getSession(), and displaying it this way. But I don't know if I should be using server components instead, and rendering the auth state on the server. idk how to do that really.

here is my code:
"use client";

import { supabase } from "@/app/lib/supabaseBrowserClient";
import Link from "next/link";
import { useEffect, useState } from "react";

export default function AuthenticatedState() {
    const [isAuthenticated, setIsAuthenticated] = useState(false);

    useEffect(() => {
        const getSession = async () => {
          const { data, error } = await supabase.auth.getSession();
          if (data.session) {
            setIsAuthenticated(true);
          } else {
            setIsAuthenticated(false)
          }
        };
        getSession();
      }, []);    

  return (
    <div>
      {isAuthenticated ? (
        <button>logout</button>
      ) : (
        <div>
          <Link href="/login">sign in</Link>
          <Link href="/sign-up">sign up</Link>
        </div>
      )}
    </div>
  );
}

0 Replies