Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

How to automatically refresh expired id token using Firebase Admin SDK #2471

Unanswered
juniorforlife asked this question in Q&A
Discussion options

I have a SvelteKit app which uses Firebase Authentication. The auth flow is like this

  1. when user clicks log in, I will call the below function on the client
export async function loginWithGooglePopup() {
 const credential = await signInWithPopup(auth, authProvider);
 const idToken = await credential.user.getIdToken();
 if (idToken) {
 // call my own SvelteKit api route
 await fetch('/api/login', { method: 'POST', body: JSON.stringify({ idToken }) });
 await invalidateAll();
 }
}
  1. then in my /api/login/+server.ts I will verify the id token given above and set my own SvelteKit cookie
export const POST: RequestHandler = async ({ request, cookies }) => {
 const { idToken } = await request.json();
 const expiresIn = 60 * 60 * 24 * 5 * 1000; // 5 days
 try {
 const decodedToken = await adminAuth.verifyIdToken(idToken);
 const cookie = await adminAuth.createSessionCookie(idToken, { expiresIn });
 const options = {
 maxAge: expiresIn,
 httpOnly: true,
 secure: PUBLIC_ENVIRONMENT === 'production' ? true : false,
 path: '/'
 };
 // use decodedToken to insert user data into database and do other stuff
 cookies.set('__session', cookie, options);
 return json({ status: 200 });
 } catch (err) {
 error(401,);
 }
};

The reason I don't use onAuthStateChanged is it only works on the client and will make a flash between logged-out and logged-in user

  1. Then in my +hooks.server.ts (a middleware file in SvelteKit) I will verify the id token on every request like this
import { adminAuth } from '$lib/server/firebase-admin/config';
export const handle: Handle = async ({ event, resolve }) => {
 const sessionCookie = event.cookies.get('__session');
 if (!sessionCookie) return await resolve(event);
 
 try {
 const userCookie = await adminAuth.verifySessionCookie(sessionCookie);
 event.locals.user = { ...userCookie }
 } catch (e) {
 console.log(e)
 }
 return await resolve(event);
};

The problem I'm having is when verifySessionCookie throws an error of auth/session-cookie-expired I couldn't find any method to request a new id token on the server. In addition, I don't want to redirect the user to the login page which is annoying. How do I achieve this?

You must be logged in to vote

Replies: 2 comments

Comment options

add onIdTokenChanged event handler using auth instance the call this api route

auth.onIdTokenChanged( async(user)=> {
await fetch('/api/login', { method: 'POST', body: JSON.stringify({ idToken:await user.getIdToken() }) });
})

this will get triggered once the id token in the client expired and firebase explicitly creates a new one then make your fetch with the new idToken to always hava updated token

You must be logged in to vote
0 replies
Comment options

This issue is probably related to your question, but no answer yet

#2349

You must be logged in to vote
0 replies
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

AltStyle によって変換されたページ (->オリジナル) /