简体   繁体   中英

SvelteKit: How to access Firebase authentication state from the server

I'm managing authentication state in a readable store which is grouped with a promise that resolves when the auth state is known (either signed in or out). The store is set internally via onAuthStateChange .

I'm trying to access this auth state from the server ( +layout.server.ts and +page.server.ts ) so that I can redirect the user to a sign-in page if they aren't authenticated, or load data from the database if (and only if) they are. No matter what I try, whenever I access this store from the server, its value is always null. I think this is because Firebase is only supposed to run on the client, although I'm not sure. Is there any way I can access this store from the server, or change my implementation so that Firebase runs in the server and passes auth state to the client? This blog post explains pretty much exactly what I want to do, but the solution here seems more complicated than it needs to be.

I've tried moving Firebase initialization code to the server (in both hooks.server.ts and +layout.server.ts ), but there's no way for me to pass the auth object to the client because it can't be serialized (I get an error explaining this when I try to return it from a load function in +page.server.ts ). I've also tried to handle authentication only using client-side code, but the server is responsible for loading data from the database, so in this case there's no way for me to verify a valid authentication state from the server.

author of the blog post you linked here.

You are correct in that the firebase client is only supposed to run on the client. If you want to access the Firebase services server-side you're supposed to use Firebase admin .

In my post I'm working around these limitations that firebase sets and unfortunately you do need that much code.
You are forced to do all the authentication in the frontend (firebase-client) and only afterwards you can inform the backend of the user info. (through the cookie)

Before I wrote this the ideal solution I had in my head was this:

  • Send the user to a login page that lists all the possible login providers.
  • The user chooses one and logs in.
  • the user gets redirected to a callback page where we can do something with the auth data in the backend.

I do think that something like this flow is possible if you're using custom tokens . But I'm sure that will be a whole load of even more complicated code.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM