Note: I’m using Next.js 13 with the app/
directory.
I’m learning Firebase and Next.js and I’m struggling to understand how to solve a toy problem. Suppose I have a Home()
component like this
/app/page.jsx
export default function Home() {
return (
<main>
<h1>Hello World</h1>
<p>This text should only be visible to authenticated users</p>
</main>
)
}
My goal is to conditionally render everything in the <p>...</p>
based on whether the user who requested the page is a logged in user. Firebase uses JWT, and Next.js 13 renders this component server side, so I believe this should be possible, but I can’t figure out how to do it.
I’m aware of onAuthStateChanged, but to my knowledge, this can only be used client-side. (A savvy user could still view this protected content.) How do I protect this content, server side?
2
Answers
To check if the user is logged in you can use ‘onAuthStateChanged’ method.
Store this information in the component’s state or use it to conditionally render parts of the component.
To perform user authentication on server side Next.js gives us ‘getServerSideProps’ to fetch the user’s authentication status
updated solution:
Create a server-side route
Client side
I would recommend using NextAuth with Firebase adapter (https://next-auth.js.org/adapters/firebase).
Simply create middleware to catch/filter authenticated paths:
then follow the NextAuth documentation by creating an api route under:
/pages/api/auth/[...nextauth].ts
(at the time of writing it is not possible to create apis under theapp
directory)optionally you can also use
useSession
to render individual elements based on if the user is logged in or not like this: