awinogrodzki / next-firebase-auth-edge

Next.js Firebase Authentication for Edge and Node.js runtimes. Compatible with latest Next.js features.
https://next-firebase-auth-edge-docs.vercel.app/
MIT License
499 stars 43 forks source link

How to sync up client with server #137

Closed rgbskills closed 9 months ago

rgbskills commented 9 months ago

I'm encountering issues with my application's user interface becoming inconsistent under certain conditions. Specifically, these issues arise when users either manually delete the 'AuthToken' cookie or when the client-side logout process fails, even though the server-side logout is successful. As a result of this, the navigation bar incorrectly displays the user as logged in, while server-side middleware redirects the user to the login page due to its own authentication checks.

steve-marmalade commented 9 months ago

Hi @rgbskills , I also found my app getting into an inconsistent state like this, and figured I'd share my experience (and curious what the great and powerful @awinogrodzki things of my approach).

Instead of storing the user in client-side state, which gets set via an onIdTokenChanged event listener, I've deviated from the examples in this repo to make the client side be purely a function of the server state.

So the flow is:

This setup guarantees consistency between server and client components, is simple to reason about (since there's a single source of truth for the data and it only flows one way), and I think this approach is well suited to future NextJS enhancements like Partial Pre-Rendering, since the user-specific components on a page will be wrapped in Suspense and triggered once cookies are accessed.

awinogrodzki commented 9 months ago

Thank you @steve-marmalade for great description of the problem and a nice solution!

@rgbskills the examples are prone to this inconsistency, because they rely on both user cookies and Firebase Auth web client. Deleting a user from Firebase is an edge-case not covered by the examples.

At this moment, I am working on improved docs and new, simpler and more robust examples.

I will update future examples to follow approach more similar to what @steve-marmalade is describing. Stay put!

awinogrodzki commented 9 months ago

Hey @rgbskills @steve-marmalade !

I just released next-firebase-auth-edge@1.0.0 along with a new, dedicated documentation page. I also address server/client sync issue in starter example along with some other improvements

You can follow https://next-firebase-auth-edge-docs.vercel.app/docs/getting-started/auth-provider to solve this problem in AuthProvider

Cheers 🎉