currently doing some development on a personal project that can potentially become SaaS application. The application currently uses firebase authentication on the frontend using nextJs 13+. I have all the required component protected.
The issue is, I've written my backend in go and I only want my API endpoints to be accessible to logged in users. I am aware that there is a SDK available to check if a user is authenticated by just passing the uid or token to the backend.But my fetches are async on server components, by the time onAuthStateChanged is updated by firebase, nextjs has already fetched the HTML with data from the server meaning the internal user state is null when the fetch is initial called .
flow: layout.tsx component loads -> fetch in page.tsx -> loading state : true -> onAuthStateChanged (user is auth and able to see dashboard or is rerouted to sign in) -> loading state: false -> displays dashboard from initial load.
There are other ways I can make it work such as using client components. but I rather dive deeper into this.
Ex. code layout:
export default function Layout({children}: {children: React.ReactNode}) {
const router = useRouter();
const [loading, setLoading] = useState(true);
const setUser = useAuthStore((state) => state.setUser);
useEffect(() => {
const unsubscribe = onAuthStateChanged(auth, (data) => {
if (data === null) {
router.push('/');
return;
}
setLoading(false);
setUser({
email: data.email
});
});
return () => {
unsubscribe();
};
}, [loading]);
return (
<htmllang="en">
<body >
{loading ? (
<Loading/>
) : (
<>{children}</>
)}
</body>
</html>
);
}
page.tsx:
async function DashBoard() {
const data = await getExternalAPI(); // call fetch function
const user = useAuthStore.getState().user;
console.log(user);
return (<div></div>)
}