Skeleton Sveltekit app for projects with firebase user authentication and ssr-protected routes. Firebase access token (UserId token) is encoded in session cookie. Cookie is being updated along with Firebase client access token rotation.
Sveltekit server handle
hook uses "token" cookie to authenticate user with Firebase admin app.
Main protected route (e.g. /dashboard ) is defined in hooks.server.ts
.
Unpack the project zip or pull the remote.
Install dependenceis with preferred package manager:
npm install
or
yarn install
Create .env
in your project root and fill in env variables according to .env-sample
.
Run the app with npm run dev
Navigate to /login
route and authenticate with Firebase, then check ssr user data inside /dashboard
page.
Accessing the Firebase Auth user in SvelteKit server-side by Jeroen Pelgrims
Saving firebase user ID in the cookie storage without http-only
is an equivalent of Firebase client local storage state persistance.
When Firebase client is set to persist state in browser local storage it keeps its access and refresh tokens there. And sts access token is the same as Firebase user Id token.
Firebase client SDK rotates access/user id token regularly and that should be enough security-wise in the most use cases.
hooks.server.ts
and url.pathname
match?Yes. In his how-to article Jeroen Pelgrims uses layout.server.ts
load
function to authenticate user.
http-only
cookie?Yes, it's possible to use http-only cookie, but that requires different implementation - one should use Sveltekit server endpoint in login flow to issue new http-only cookie and set in the response to the client. See Firebase documentation on session cookies.
In this case authentication is handled purely server-side and Firebase client sdk persistance can be set to NONE
.
This approach adds some level of complexity and might be more useful for projects with high security requirements.