🔥 All-Access Pass — $199 USD (Regular $499) · Unlock all 2,836 Astro themes ➔
komal.nakrani
Get All-Access Pass ($199)
ThemesCategoriesDocsBlogTips & TricksPricingGet All-Access Pass ($199)
CMS & Integrations••By Komal Nakrani

Astro Firebase Guide: Firestore, Auth and Hosting

Use Astro with Firebase: read Firestore at build time, sign users in with Firebase Auth session cookies verified in middleware, and deploy to Firebase Hosting.

#Astro#Firebase#Firestore#Authentication#Deployment

To use Firebase with Astro, read Firestore data at build time with the Firebase Admin SDK for static pages, and for logins, sign users in with the Firebase client SDK in the browser, exchange their ID token for a session cookie in an Astro endpoint, and verify that cookie in middleware. Static output deploys to Firebase Hosting with firebase deploy. Firebase supplies the database and identity; Astro renders the pages.

This guide walks through each piece on Astro 7 with working code.

Key Takeaways

  • Use firebase-admin on the server (build time, endpoints, middleware) and the firebase web SDK in the browser.
  • Build-time Firestore reads produce plain static pages with no Firebase code shipped to visitors.
  • Server-side auth uses createSessionCookie() in an endpoint and verifySessionCookie() in middleware.
  • firebase-admin needs a Node.js runtime, so pair it with the Node, Netlify or Vercel adapter.
  • Firebase Hosting serves Astro’s dist/ folder; set "public": "dist" in firebase.json.

What Firebase brings to an Astro site

Firebase is Google’s app platform: Firestore (a document database), Authentication, Cloud Storage, Hosting, Cloud Functions and analytics, all under one project. It’s common when a team already has a mobile app on Firebase and wants a fast marketing site or web dashboard that shares the same users and data.

Astro uses Firebase in three ways:

Job Runs where Firebase SDK
Read content for static pages Build machine firebase-admin
Sign-in UI Browser firebase (web SDK)
Protect on-demand pages Server (adapter) firebase-admin

There are two SDKs because they have different trust levels. The web SDK runs as the visitor and is limited by security rules. The Admin SDK runs with a service account and bypasses those rules, so it must never reach the browser. If you’re weighing Firebase against a SQL backend, our Astro database options article compares it with Supabase, Turso and others.

Install and configure both SDKs

npm install firebase firebase-admin

In the Firebase console, open Project settings. Under General, register a web app and copy its config object (API key, auth domain, project ID). Under Service accounts, generate a new private key, which downloads a JSON file. Put the values in .env:

# .env
PUBLIC_FIREBASE_API_KEY=AIza...
PUBLIC_FIREBASE_AUTH_DOMAIN=your-app.firebaseapp.com
PUBLIC_FIREBASE_PROJECT_ID=your-app
FIREBASE_CLIENT_EMAIL=[email protected]
FIREBASE_PRIVATE_KEY="-----BEGIN PRIVATE KEY-----\n...\n-----END PRIVATE KEY-----\n"

The PUBLIC_ values are meant to be public; Firebase web config identifies your project but grants nothing beyond your security rules. The service account values are secrets. Keep them out of Git and add them in your host’s environment settings.

Create the server-side app once:

// src/lib/firebase-server.ts
import { initializeApp, cert, getApps } from 'firebase-admin/app';
import { getAuth } from 'firebase-admin/auth';
import { getFirestore } from 'firebase-admin/firestore';

const app =
  getApps()[0] ??
  initializeApp({
    credential: cert({
      projectId: import.meta.env.PUBLIC_FIREBASE_PROJECT_ID,
      clientEmail: import.meta.env.FIREBASE_CLIENT_EMAIL,
      privateKey: import.meta.env.FIREBASE_PRIVATE_KEY.replace(/\\n/g, '\n'),
    }),
  });

export const adminAuth = getAuth(app);
export const db = getFirestore(app);

The getApps() check stops “app already exists” errors during dev reloads, and the replace() turns escaped newlines from the env file back into a valid key.

Read Firestore at build time

For pages whose data changes rarely, such as a product list, team page or event listing, query Firestore while building:

---
// src/pages/products/[slug].astro
import { db } from '../../lib/firebase-server';
import BaseLayout from '../../layouts/BaseLayout.astro';

export async function getStaticPaths() {
  const snap = await db.collection('products').where('published', '==', true).get();
  return snap.docs.map((doc) => {
    const data = doc.data();
    return {
      params: { slug: data.slug },
      props: {
        name: data.name as string,
        summary: data.summary as string,
        price: data.price as number,
        updated: data.updatedAt.toDate() as Date,
      },
    };
  });
}

const { name, summary, price, updated } = Astro.props;
---
<BaseLayout title={name}>
  <h1>{name}</h1>
  <p>{summary}</p>
  <p>${price.toFixed(2)}</p>
  <p><small>Updated {updated.toLocaleDateString('en-US')}</small></p>
</BaseLayout>

Convert Firestore Timestamp values with .toDate() before passing them as props; they aren’t plain objects. The built pages contain only HTML, so visitors never download a Firebase SDK. To rebuild when data changes, call your host’s deploy hook from a Cloud Function triggered on document writes, or rebuild on a schedule.

For larger content sets, move the query into a content loader and read it with getCollection(). Our content loaders guide shows the pattern.

Sign users in on the client

Firebase Auth’s sign-in flows (Google, email link, email and password, phone) run in the browser. Initialize the web SDK in a client module:

// src/lib/firebase-client.ts
import { initializeApp } from 'firebase/app';
import { getAuth } from 'firebase/auth';

const app = initializeApp({
  apiKey: import.meta.env.PUBLIC_FIREBASE_API_KEY,
  authDomain: import.meta.env.PUBLIC_FIREBASE_AUTH_DOMAIN,
  projectId: import.meta.env.PUBLIC_FIREBASE_PROJECT_ID,
});

export const auth = getAuth(app);

The login page signs in, sends the ID token to the server, then signs out of the client so the server cookie is the only session:

---
// src/pages/login.astro
import BaseLayout from '../layouts/BaseLayout.astro';
---
<BaseLayout title="Sign in">
  <h1>Sign in</h1>
  <button id="google">Continue with Google</button>
  <p id="error" role="alert"></p>
</BaseLayout>

<script>
  import { GoogleAuthProvider, signInWithPopup, signOut } from 'firebase/auth';
  import { auth } from '../lib/firebase-client';

  document.getElementById('google')?.addEventListener('click', async () => {
    try {
      const cred = await signInWithPopup(auth, new GoogleAuthProvider());
      const idToken = await cred.user.getIdToken();
      const res = await fetch('/api/session/', {
        method: 'POST',
        headers: { Authorization: `Bearer ${idToken}` },
      });
      await signOut(auth);
      if (res.ok) window.location.assign('/account/');
    } catch (err) {
      document.getElementById('error')!.textContent = 'Sign-in failed. Please try again.';
    }
  });
</script>

Astro bundles the <script> and only this page loads the Firebase Auth code. Enable the Google provider under Authentication, Sign-in method, and add your domains under Authorized domains.

Create and verify session cookies

The endpoint verifies the ID token and swaps it for a long-lived, HTTP-only session cookie:

// src/pages/api/session.ts
import type { APIRoute } from 'astro';
import { adminAuth } from '../../lib/firebase-server';

export const prerender = false;
const FIVE_DAYS = 60 * 60 * 24 * 5;

export const POST: APIRoute = async ({ request, cookies }) => {
  const idToken = request.headers.get('Authorization')?.replace('Bearer ', '');
  if (!idToken) return new Response('Missing token', { status: 401 });

  try {
    await adminAuth.verifyIdToken(idToken);
    const session = await adminAuth.createSessionCookie(idToken, { expiresIn: FIVE_DAYS * 1000 });
    cookies.set('__session', session, {
      path: '/',
      httpOnly: true,
      secure: true,
      sameSite: 'lax',
      maxAge: FIVE_DAYS,
    });
    return new Response(null, { status: 204 });
  } catch {
    return new Response('Invalid token', { status: 401 });
  }
};

export const DELETE: APIRoute = ({ cookies }) => {
  cookies.delete('__session', { path: '/' });
  return new Response(null, { status: 204 });
};

expiresIn is in milliseconds and must be between five minutes and two weeks, while the cookie’s maxAge is in seconds. The name __session is the one cookie Firebase Hosting passes through its CDN to backends, so it’s a safe default if you ever put Hosting in front of the server.

Middleware then checks the cookie on every on-demand request:

// src/middleware.ts
import { defineMiddleware } from 'astro:middleware';
import { adminAuth } from './lib/firebase-server';

export const onRequest = defineMiddleware(async (context, next) => {
  context.locals.user = null;
  if (context.isPrerendered) return next();

  const session = context.cookies.get('__session')?.value;
  if (session) {
    try {
      const claims = await adminAuth.verifySessionCookie(session, true);
      context.locals.user = { uid: claims.uid, email: claims.email ?? null };
    } catch {
      context.cookies.delete('__session', { path: '/' });
    }
  }

  if (context.url.pathname.startsWith('/account') && !context.locals.user) {
    return context.redirect('/login/');
  }
  return next();
});
// src/env.d.ts
declare namespace App {
  interface Locals {
    user: { uid: string; email: string | null } | null;
  }
}

The second argument to verifySessionCookie() checks for revoked sessions, which costs one extra lookup but means a password reset or forced sign-out takes effect immediately. See our Astro middleware guide for more on locals and redirects.

Secure Firestore with rules

The Admin SDK ignores security rules, but the web SDK doesn’t, and your web config is public. Lock Firestore down so only the reads you intend are possible:

// firestore.rules
rules_version = '2';
service cloud.firestore {
  match /databases/{database}/documents {
    match /products/{id} {
      allow read: if resource.data.published == true;
      allow write: if false;
    }
    match /users/{uid}/{document=**} {
      allow read, write: if request.auth != null && request.auth.uid == uid;
    }
  }
}

If all your Firestore access goes through the server, you can deny all client reads and writes entirely. Deploy rules with firebase deploy --only firestore:rules.

Deploy Astro to Firebase Hosting

A fully static Astro site deploys to Firebase Hosting like any folder of files:

{
  "hosting": {
    "public": "dist",
    "ignore": ["firebase.json", "**/.*", "**/node_modules/**"],
    "cleanUrls": true,
    "trailingSlash": true
  }
}
npm install -g firebase-tools
firebase login
firebase init hosting
npm run build && firebase deploy --only hosting

Match trailingSlash to Astro’s trailingSlash setting so URLs and canonicals agree. On-demand pages need a server: build with the Node adapter and run it on Cloud Run or another Node host, or deploy the whole site to Netlify or Vercel and keep using Firebase for data and auth. The Admin SDK depends on Node.js APIs, so on Cloudflare Workers use Firebase’s REST APIs or a Workers-compatible token verification library instead. Our Astro deployment guide compares hosts.

Every Komal theme builds to static files, so the build-time Firestore pattern above works with any of them; account pages are the part you add with an adapter.

FAQ

Can I use Firebase with a static Astro site?

Yes. Read Firestore with the Admin SDK at build time and the output is plain HTML you can host on Firebase Hosting or anywhere else. Client-side features like sign-in popups also work on a static site, but checking the user on the server needs an adapter.

Why use session cookies instead of the Firebase client session?

The client SDK stores its session in the browser’s IndexedDB, which the server can’t read. Session cookies let Astro middleware know who the user is before rendering a page, so protected HTML is never sent to someone who isn’t signed in.

Does firebase-admin work on Cloudflare or edge runtimes?

Not reliably. The Admin SDK depends on Node.js APIs, so use the Node, Netlify or Vercel adapter for routes that import it. On edge runtimes, verify tokens against Google’s public keys with a JWT library or call the Firebase REST APIs.

Is it safe to put the Firebase config in client code?

Yes. The web config identifies your project and is meant to be public. Security comes from Firestore and Storage security rules plus App Check, not from hiding the config. The service account private key is different and must stay on the server.

Does Astro have an official Firebase integration?

No first-party integration exists, but Astro’s docs include a Firebase guide that uses the same Admin SDK and session cookie approach shown here.