---
title: "Query Redis with Astro on Cloudflare Workers"
description: "Learn how to query Redis from an Astro application running on Cloudflare Workers."
source: "https://www.launchfa.st/blog/query-redis-astro-cloudflare-workers"
author: "Rishi Raj Jain"
created_at: 2025-04-25T00: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 Redis 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-redis-astro-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 any Redis 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 Redis, and deploying the application to Cloudflare Workers.

## Prerequisites

- [Node.js 20](https://nodejs.org/en) or later
- Any Redis database (you can use [Upstash](https://upstash.com) for a managed solution)

## Table Of Contents

- [Create a new Astro application](#create-a-new-astro-application)
- [Integrate Cloudflare adapter in your Astro project](#integrate-cloudflare-adapter-in-your-astro-project)
- [Update Type Definitions](#update-type-definitions)
- [Create a Redis Connection](#create-a-redis-connection)
- [Query Redis from Astro application](#query-redis-from-astro-application)
- [Deploy to Cloudflare Workers](#deploy-to-cloudflare-workers)

## 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 redis-on-workers
npm install -D tsx
```

The following libraries are installed:

- `redis-on-workers`: Connect to your Redis server using `cloudflare:sockets`.
- `tsx`: A runtime for TypeScript and JavaScript that allows you to run TypeScript files directly without needing to compile them first.

## 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 = "redis-astro-workers"
main = "dist/_worker.js"
compatibility_date = "2025-04-01"
compatibility_flags = [ "nodejs_compat" ]

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

[vars]
REDIS_URL=""
```

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: {
      REDIS_URL: envField.string({ context: 'server', access: 'secret', optional: false }),
    }
  }
  // adapter
})
```

## Update Type Definitions

You need to ensure type definitions for the Redis client are correctly applied. For this, create a new file named `apply-patch.tsx` in the root of the project with the following code:

```typescript
// File: apply-patch.tsx

import { existsSync, readFileSync, writeFileSync } from 'fs'
import { join } from 'path'

const redisWorkersType = join('node_modules', 'redis-on-workers', 'dist', 'index.d.ts')

if (existsSync(redisWorkersType)) {
  const content = readFileSync(redisWorkersType, 'utf8')
  if (!content.includes('export declare class RedisInstance')) writeFileSync(redisWorkersType, content.replace('declare class RedisInstance', 'export declare class RedisInstance'))
} else console.log(`Warning: Could not find Redis workers type definition at ${redisWorkersType}`)
```

This code checks if a specific type definition file exists for the Redis client. If it does, the code reads the file and checks for the presence of a specific export. If that export is missing, it modifies the file to add the export.

Now, run the file with the following command:

```bash
npx tsx apply-patch.tsx
```

## Create a Redis Connection

In your Astro application, create a file named `redis.ts` in the `src/storage` directory to establish a connection with Redis. Use the code below:

```typescript
// File: src/storage/redis.ts

import { getSecret } from 'astro:env/server'
import { createRedis } from 'redis-on-workers'

const connectionString = getSecret('REDIS_URL')
if (!connectionString) throw new Error('REDIS_URL is not defined in the environment variables')

export default createRedis(connectionString)
```

The code above imports the `getSecret` function from `astro:env/server` for accessing environment variables dynamically during the runtime, and defines a `redis` variable of type `RedisInstance`. It retrieves the Redis connection string from the environment secrets using getSecret, and establishes a Redis connection using `createRedis()` if the connection string is available. Finally, it exports the redis instance.

## Query Redis from Astro application

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

```astro
// File: src/pages/index.astro
---
import redis from '../storage/redis'

let productsCount = await redis.sendOnce('GET', 'productsCount')
if (!productsCount) productsCount = 0
---

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

This code imports the `redis` instance created earlier and retrieves the value associated with the key `productsCount` from Redis using the `sendOnce()` 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

- [redis-on-workers](https://www.npmjs.com/package/redis-on-workers)

## Conclusion

In this blog post, you learned how to query a Redis instance from an Astro application running on Cloudflare Workers. You went through the steps of setting up the Redis client, establishing a connection, and executing commands to retrieve data from Redis 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!
