Back

(NextJS SSR) How to best check for a logged in user multiple client components deep?

  • 0
  • Auth
  • Web
  • Cloud
Criffis
4 May, 2024, 17:58

I have a client component deep in my navbar that needs to change depending on if the user is logged in or not. Using NextJS, I would normally check if user is authenticated from the parent server component like here: https://appwrite.io/docs/tutorials/nextjs-ssr-auth/step-4

However, since I need to check for the user many layers deep and update the component whenever the user logs in / logs out, I am at a loss on how to do this, since you cannot use context in a server component.

I thought about importing the getLoggedInUser function from inside the component and do something like this

TypeScript
  const [isLoggedIn, setIsLoggedIn] = useState(false)

  useEffect(() => {
    const fetchLoggedInUser = async () => {
      const user = await getLoggedInUser()
      setIsLoggedIn(!!user)
    }
    fetchLoggedInUser()
  }, [])

But this only runs on the first render, and running this e.g. on every route change seems very inefficient. How would you do this?

TL;DR
Developers want to check for a logged-in user status across multiple client components deep in NextJS. The common approach of checking in the parent server component won't work due to the depth. One workaround is to import the user authentication function into the required component and use state to update based on the user's logged-in status. However, this initial solution is inefficient as it only runs on the first render. A better approach suggested could involve using client-side storage like local storage or session storage to store the user's login status and update the components accordingly when the user logs in or logs out.
Reply

Reply to this thread by joining our Discord

Reply on Discord

Need support?

Join our Discord

Get community support by joining our Discord server.

Join Discord

Get premium support

Join Appwrite Pro and get email support from our team.

Learn more