Next.js Discord

Discord Forum

SSR & Firebase Auth

Unanswered
Sun bear posted this in #help-forum
Open in Discord
Sun bearOP
If token is expired, initial page load on SSR side won't work because the refreshing happens on client side. How do people handle this canonically?

If any of you demigods have solved this already please do flex on me 🥺

I can provide more info if needed 🙏🏼

14 Replies

Dogo Guatemalteco
isn't it possible to simply refresh the token and set the cookie on the server side?
Sun bearOP
The issue is server side runs first, it makes the request with the cookie token which is expired and fails, only after that the client side renders and can refresh the token
So how does one normally handle SSR side authentication if it loads first and it simply uses the cookies and the cookie token might be expired? Firebase auth only has functionality for token refresh on client...
Sun bearOP
At least this is my understanding of things, if you know more please illuminate me 😬
Sun bearOP
HULP
King Eider
@Sun bear Did you ever find a solution?
Sun bearOP
Meh more or less
I simplified by fetching auth info on server side only optionally, to fetch initial page state, then fetch on client side unconditionally
King Eider
Ok
Sun bearOP
SSR: tries to fetch initial state
Client: tries to use initial state if avialble, fetches current state with a useEffect after refreshing idToken and updating cookie
Not sure if I'm being clear
King Eider
My approach was to have the Auth initially handled client side (magic link).

User then clicks email and goes to a /auth-check/page.tsx

However, I have the middleware pick up that incoming /auth-check and then call an internal api/auth/verify route POST with the token

Then in the api route (which runs server side) I use firebase admin sdk to verify the token.

This is not a perfect solution but its helped get me this far.

I am running into different issues now that I am deploying via docker to GCP
Sun bearOP
hmm I see
yeah we initially had admin-sdk, but honestly I was annoyed by the fact it shouldn't be needed. All I wanted to do was refresh the token from SSR, in case the cookie available at page load was expired, but didn't find a good way to do that. If firebase-auth can do it on client side, why would I have to use firebase-admin for server side?
We tried with redirecting to a refresh page on client to refresh client side with firebase-auth, but it resulted in a funky multiple reloading glitchy ux
So I'm now trying to simplify as much as possible and not rely on authenticated Server side fetches, if not for an optional initial load state
King Eider
It does feel a lot more complicated than it should be