next-firebase-auth icon indicating copy to clipboard operation
next-firebase-auth copied to clipboard

Limit frequency of calls to set auth cookie (optimization)

Open alex-knyazev opened this issue 3 years ago • 5 comments

Describe the bug When you visit any page, onIdTokenChange function is called, so the token is changed.

I think this is redudant, we don't need to do update token on every page.

Versions

next-firebase-auth version: ^0.14.1-alpha.0, Firebase JS SDK: 8.10.0 Next.js: 12.0.8

To Reproduce Steps to reproduce the behavior:

  1. Go to any page which uses withAuthUser
  2. Then go to other page
  3. See in console - there is message Completed auth API request via tokenChangedHandler.

image

Expected behavior Should be called only when token expired or user auth state changed.

alex-knyazev avatar Feb 04 '22 21:02 alex-knyazev

Thanks for the issue. Agreed, this could be a nice optimization.

What Firebase JS SDK API would work for this?

If we implement this, we'd want logic to ensure a cookie is set in the case it's not set (e.g., cookies were cleared) even if the ID token has not changed.

kmjennison avatar Feb 05 '22 00:02 kmjennison

@kmjennison

Generally I don't undesrtand why now firebase.auth().onIdTokenChanged is called on every page. In doc we see that hook should be called on sign-in, sign-out, and token refresh events only.

It is a big issue because when we call this operation request to backend is happened and then request to firebase, more requests = more money to pay.

alex-knyazev avatar Feb 07 '22 04:02 alex-knyazev

The Firebase onIdTokenChanged callback is called when it initializes, too, so this is expected behavior.

I agree, most apps would work well while reducing the calls to the login endpoint. The question is how to implement it. Really, we don't care about refreshing the cookie when the ID token will expire but rather sometime before the auth cookie (refresh token) will expire. Ex: if the auth cookie has a max age of 12 days, maybe the app wants to refresh it after 5 days—and don't call the login endpoint for those first 5 days.

Right now, the client side has no visibility into whether the auth cookie is set because the cookie is http-only. One approach is to set a separate JS-accessible cookie with the ~last login time~ (edit: auth cookie's expiration time) and use that to inform whether to make the API call.

Thoughts?

kmjennison avatar Feb 07 '22 15:02 kmjennison

I think it could be better to save token expieartion date in JS-accessible cookie instead of last login time. When we know the expiration date then we can always compare it with the current date to know if we need to refresh the token.

alex-knyazev avatar Feb 07 '22 20:02 alex-knyazev

Is there any news on this subject? I get a call on every request to the login endpoint and it's really not ideal IMHO

juliensnz avatar Nov 24 '22 18:11 juliensnz