---
title: "Query Cloud Firestore with Astro on Cloudflare Workers"
description: "Learn how to query Cloud Firestore from an Astro application running on Cloudflare Workers."
source: "https://www.launchfa.st/blog/query-cloud-firestore-astro-cloudflare-workers"
author: "Rishi Raj Jain"
created_at: 2025-04-25T12:00:00.000Z
updated_at: 2026-07-02T00:00:00.000Z
---

> **Site index for agents**
> Fetch https://www.launchfa.st/llms.txt to discover every page on this site.
> Every page is also available as Markdown by appending `.md` to its URL.

<img width="1600" height="900" alt="Query Cloud Firestore with Astro on Cloudflare Workers" decoding="async" loading="eager" class="mt-4 border rounded-sm bg-cover bg-center bg-no-repeat transform will-change-auto" src="https://ik.imagekit.io/vjeqenuhn/launchfast-website/query-cloud-firestore-cloudflare-workers.png" />

<a href="/#pricing" class="rounded-full break-words text-xs border text-black px-4 py-2 max-w-max text-center no-underline hover:bg-black hover:text-white">
  ℹ️&nbsp;&nbsp;Available today with LaunchFast Starter Kits</a>
</div>

In this guide, you will learn how to interact with a Cloud Firestore instance from an Astro application running on Cloudflare Workers. You will go through the process of setting up a new Astro project, enabling server-side rendering using the Cloudflare adapter, installing the necessary packages, writing code to interact with Cloud Firestore, and deploying the application to Cloudflare Workers.

## Prerequisites

- [Node.js 20](https://nodejs.org/en) or later
- A [Firebase](https://firebase.google.com) account

## Table Of Contents

- [Generate a Firebase Service Account JSON](#generate-a-firebase-service-account-json)
- [Create a new Astro application](#create-a-new-astro-application)
- [Integrate Cloudflare adapter in your Astro project](#integrate-cloudflare-adapter-in-your-astro-project)
- [Access the Environment Variables](#access-the-environment-variables)
- [Initialize Firebase Connection](#initialize-firebase-connection)
- [Query Cloud Firestore from Astro application](#query-cloud-firestore-from-astro-application)
- [Deploy to Cloudflare Workers](#deploy-to-cloudflare-workers)

## Generate a Firebase Service Account JSON

- Go to the [Firebase Console](https://console.firebase.google.com/) and browse your project (create one if you do not have one already).
- In the Firebase Console, navigate to **Project Settings** by clicking the gear icon.
- Next, go to the **Service accounts** tab.
- Finally, click on **Generate new private key** and download the JSON file. This file contains your Firebase service account credentials.

## Create a new Astro application

Let’s get started by creating a new Astro project. Open your terminal and run the following command:

```bash
npm create astro@latest my-app
```

`npm create astro` is the recommended way to scaffold an Astro project quickly.

When prompted, choose:

- `Use minimal (empty) template` when prompted on how to start the new project.
- `Yes` when prompted to install dependencies.
- `Yes` when prompted to initialize a git repository.

Once that’s done, you can move into the project directory and start the app:

```bash
cd my-app
npm run dev
```

The app should be running on [localhost:4321](http://localhost:4321/). Next, execute the command below to install the necessary library for building the application:

```bash
npm install fireworkers
```

The following library is installed:

- `fireworkers`: A library that facilitates interaction with Cloud Firestore from Cloudflare Workers.

## Integrate Cloudflare adapter in your Astro project

To deploy your Astro project to Cloudflare Workers, you need to install the corresponding adapter. Execute the command below:

```bash
npx astro add cloudflare
```

When prompted, choose the following:

- `Y` when prompted whether to install the Cloudflare dependencies.
- `Y` when prompted whether to make changes to the Astro configuration file.

You have successfully enabled server-side rendering in Astro.

To make sure that the output is deployable to Cloudflare Workers, create a `wrangler.toml` file in the root of the project with the following code:

```toml
// File: wrangler.toml

name = "cloud-firestore-astro-workers"
main = "dist/_worker.js"
compatibility_date = "2025-04-01"
compatibility_flags = [ "nodejs_compat" ]

[assets]
directory="dist"
binding="ASSETS"

[vars]
FIREBASE_PROJECT_ID=""
FIREBASE_PRIVATE_KEY=""
FIREBASE_CLIENT_EMAIL=""
FIREBASE_PRIVATE_KEY_ID=""
```

Post that, make sure that you have both an `.env` file and a `wrangler.toml` file with the variables defined so that they can be accessed during `npm run dev` and when deployed on Cloudflare Workers respectively.

Further, update the `astro.config.mjs` file with the following to be able to access these variables in code programmatically:

```tsx
// File: astro.config.mjs

// ... Existing imports...
import { defineConfig, envField } from 'astro/config'

export default defineConfig({
  env: {
    schema: {
      FIREBASE_PROJECT_ID: envField.string({ context: 'server', access: 'secret', optional: false }),
      FIREBASE_PRIVATE_KEY: envField.string({ context: 'server', access: 'secret', optional: false }),
      FIREBASE_CLIENT_EMAIL: envField.string({ context: 'server', access: 'secret', optional: false }),
      FIREBASE_PRIVATE_KEY_ID: envField.string({ context: 'server', access: 'secret', optional: false }),
    }
  }
  // adapter
})
```

## Access the Environment Variables

To securely access the necessary environment variables at runtime, you should use the `getSecret` function from `astro:env/server`. This approach, recommended from [Astro 5.6 onwards](https://astro.build/blog/astro-560/), ensures that your application remains provider agnostic and sensitive information is not hardcoded. The following variables will be retrieved using this method:

- FIREBASE_PROJECT_ID
- FIREBASE_PRIVATE_KEY
- FIREBASE_CLIENT_EMAIL
- FIREBASE_PRIVATE_KEY_ID

```typescript
// File: src/storage/firebase/config.ts

import { getSecret } from 'astro:env/server'

const project_id = getSecret('FIREBASE_PROJECT_ID')
const private_key = getSecret('FIREBASE_PRIVATE_KEY')
const client_email = getSecret('FIREBASE_CLIENT_EMAIL')
const private_key_id = getSecret('FIREBASE_PRIVATE_KEY_ID')

export default function getFirebaseConfig() {
  return {
    project_id,
    private_key,
    client_email,
    private_key_id,
  }
}
```

## Initialize Firebase Connection

In your Astro application, create a file named `index.ts` in the `src/storage/firebase` directory to export a function that will establish a connection with Cloud Firestore. Use the code below:

```typescript
// File: src/storage/index.ts
import getFirebaseConfig from './config'
import * as Firestore from 'fireworkers'
import { getSecret } from 'astro:env/server'

const firebaseConfig = getFirebaseConfig()

export async function initializeFirebase(): Promise<Firestore.DB> {
  return await Firestore.init({
    uid: 'user1234',
    project_id: firebaseConfig.project_id,
    private_key: firebaseConfig.private_key,
    client_email: firebaseConfig.client_email,
    private_key_id: firebaseConfig.private_key_id,
  })
}

export { Firestore }
```

The code above imports the `getSecret` function from `astro:env/server` to access environment variables dynamically during runtime. It then imports the `getFirebaseConfig` function to retrieve Firebase configuration details. The `initializeFirebase` function is defined to initialize a Firestore database connection using the configuration details obtained from `getFirebaseConfig`. Finally, the `Firestore` module is exported for use in other parts of the application.

## Query Cloud Firestore from Astro application

Now, you are ready to execute commands on Firestore by using the `firestore` instance. In your Astro page, write the code below to interact with Cloud Firestore:

```astro
---
// File: src/pages/index.astro
import { initializeFirebase, Firestore } from '../../storage/index'

const firestore = await initializeFirebase()

// To set a document in `storage` collection, await Firestore.set(firestore, 'storage', key, { value }, { merge: true })
// To remove a document in the `storage` collection, await Firestore.remove(firestore, 'storage', key)

// Get the document (of key `productsCount`) and use its value property (from the `storage` collection)
let count = await Firestore.get(firestore, 'storage', 'productsCount').then((doc) => doc.fields.value).catch(() => null)
if (!count) count = 0
---

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
    {count}
</body>
</html>
```

This code imports the `initializeFirebase` function and the entire `Firestore` export, then retrieves the value associated with the key `productsCount` from Cloud Firestore using the `.get()` method.

## Deploy to Cloudflare Workers

To make your application deployable to Cloudflare Workers, create a file named `.assetsignore` in the `public` directory with the following content:

```
_routes.json
_worker.js
```

Next, you will need to use the Wrangler CLI to deploy your application to Cloudflare Workers. Run the following command to deploy:

```bash
npm run build && npx wrangler@latest deploy
```

## References

- [fireworkers](https://www.npmjs.com/package/fireworkers)

## Conclusion

In this blog post, you learned how to query Cloud Firestore from an Astro application running on Cloudflare Workers. You went through the steps of setting up the Cloud Firestore client, establishing a connection, and executing commands to retrieve data from Firestore within the Astro application.

If you would like to explore specific sections in more detail, expand on certain concepts, or cover additional related topics, please let me know, and I'll be happy to assist!
