Home > front end >  set js-cookie value to firebase token
set js-cookie value to firebase token

Time:09-13

Is it ok to set the value of a cookie to a token? I'm using js-cookie, Firebase auth/firestore and Next.js and I have my cookie set like this inside of my handleUser function:

  const handleUser = async (rawUser) => {
    if (rawUser) {
      const user = await formatUser(rawUser)
      const { token, ...userWithoutToken } = user

      createUser(user.uid, userWithoutToken)
      setUser(user)

      cookie.set('colorizer-auth', token, {
        expires: 1
      })

      setLoading(false)
      return user
    } else {
      setUser(false)
      cookie.remove('colorizer-auth')

      setLoading(false)
      return false
    }
   }

and the token is decoded and set here:

const formatUser = async (user) => {
  const decodedToken = await user.getIdTokenResult(true);
  const { token, expirationTime } = decodedToken;
  return {
    uid: user.uid,
    email: user.email,
    name: user.displayName,
    provider: user.providerData[0].providerId,
    photoUrl: user.photoURL,
    token,
    expirationTime,
  }
}

CodePudding user response:

I've seen some projects that use the Firebase Auth ID Token (access_token) itself in the cookies but that token is valid only for 1 hour. You'll have to securely store the refresh_token as well so you can refresh the cookie once it expires.

However, I would recommend using session cookies instead for such SSR application. You can set the expiration time ranging 5 minutes to 2 weeks. It might be best to reauthenticate user after this expires.

  • Related