> ## Documentation index
> Fetch the complete documentation index at: https://upstash.com/docs/llms.txt
> Ask it with GET https://upstash.com/docs/ask?q=<keywords or question>. Short keywords rank best.
> Use these to discover all available pages before exploring further.
> Feature requests: https://upstash.com/docs/common/help/feature-requests.md lists what users asked for and how to vote for a request or add one.
> Page rating: `GET https://upstash.com/docs/feedback?path=/docs/redis/quickstarts/astro&helpful={true|false}&comment={comment}` records whether this page helped. The `comment` (URL-encoded, at most 500 characters) says what helped, or what was missing or wrong; a `helpful=false` rating needs it. It is anonymous and needs no key. Comments hold no code, secrets or personal data.

# Upstash Redis with Astro

> Use Upstash Redis in an Astro project with @upstash/redis: build a counter in an API endpoint and a page, and store Astro sessions in Redis with the upstash session driver.

Astro pages and endpoints that render on demand run on the server, where they
can connect to Upstash Redis with the HTTP-based
[`@upstash/redis`](/redis/howto/connect-with-upstash-redis) SDK. The same
database can also hold your [Astro sessions](https://docs.astro.build/en/guides/sessions/).

This quickstart uses the Node.js adapter. The code is the same with other
server adapters such as Vercel or Netlify.

### Database Setup

Create a Redis database using the [Upstash Console](https://console.upstash.com)
or [Upstash CLI](https://github.com/upstash/cli). On the database page, open
the **Connect** section and copy `UPSTASH_REDIS_REST_URL` and
`UPSTASH_REDIS_REST_TOKEN`.

### Project Setup

Create an Astro project, add the Node.js adapter and install the SDK:

```shell
npm create astro@latest astro-upstash -- --template minimal
cd astro-upstash
npx astro add node
npm install @upstash/redis
```

Put the two values in a `.env` file at the project root:

```shell .env
UPSTASH_REDIS_REST_URL="YOUR_REST_URL"
UPSTASH_REDIS_REST_TOKEN="YOUR_REST_TOKEN"
```

Add `.env` to your `.gitignore` so the token is not committed.

`Redis.fromEnv()` and the session driver read these variables from
`process.env`. During `astro dev`, Astro exposes `.env` only to
`import.meta.env`, so load the file into `process.env` at the top of
`astro.config.mjs`:

```javascript astro.config.mjs
import { existsSync } from "node:fs";
import { defineConfig } from "astro/config";
import node from "@astrojs/node";

// Make .env values available to process.env in development
if (existsSync(".env")) process.loadEnvFile();

export default defineConfig({
  adapter: node({
    mode: "standalone",
  }),
});
```

`process.loadEnvFile()` keeps variables that are already set, so values from
your host win in production.

### Create a Client

Create `src/lib/redis.ts`:

```typescript src/lib/redis.ts
import { Redis } from "@upstash/redis";

export const redis = Redis.fromEnv();
```

### Counter Endpoint

Create `src/pages/api/counter.ts`. Astro prerenders routes by default, so
`prerender = false` makes this one run on every request:

```typescript src/pages/api/counter.ts
import type { APIRoute } from "astro";
import { redis } from "../../lib/redis";

export const prerender = false;

export const GET: APIRoute = async () => {
  const count = await redis.get<number>("counter");
  return Response.json({ count: count ?? 0 });
};

export const POST: APIRoute = async () => {
  const count = await redis.incr("counter");
  return Response.json({ count });
};
```

You can use the client in a page's frontmatter too. Create
`src/pages/counter.astro`:

```astro src/pages/counter.astro
---
import { redis } from "../lib/redis";

export const prerender = false;

const count = await redis.incr("page-views");
---

<p>This page has been viewed {count} times.</p>
```

To render every route on demand instead, set `output: "server"` in
`astro.config.mjs` and drop the `prerender` exports.

### Run Locally

```shell
npm run dev
```

Increment the counter twice, then read it:

```shell
curl -X POST http://localhost:4321/api/counter
# {"count":1}

curl -X POST http://localhost:4321/api/counter
# {"count":2}

curl http://localhost:4321/api/counter
# {"count":2}
```

Open `http://localhost:4321/counter` and reload it to see the page views go up.

### Sessions

Astro sessions keep per-visitor data on the server and store only a session ID
in a cookie. To keep that data in Upstash Redis, set the session driver in
`astro.config.mjs`:

```javascript astro.config.mjs
import { existsSync } from "node:fs";
import { defineConfig, sessionDrivers } from "astro/config";
import node from "@astrojs/node";

if (existsSync(".env")) process.loadEnvFile();

export default defineConfig({
  adapter: node({
    mode: "standalone",
  }),
  session: {
    driver: sessionDrivers.upstash(),
  },
});
```

The driver uses `@upstash/redis`, which you installed above, and reads
`UPSTASH_REDIS_REST_URL` and `UPSTASH_REDIS_REST_TOKEN` from `process.env` at
runtime. Driver options are inlined at build time, so don't pass the token as
an option.

Read and write session data with `Astro.session` in a page, or
`context.session` in an endpoint. Create `src/pages/visits.astro`:

```astro src/pages/visits.astro
---
export const prerender = false;

const visits = ((await Astro.session?.get("visits")) ?? 0) + 1;
Astro.session?.set("visits", visits);
---

<p>You have visited this page {visits} times in this session.</p>
```

Reload the page and the number goes up. Each session is one Redis key named
after the session ID. The keys have no expiry by default; to let Redis delete
idle sessions, pass a TTL in seconds:

```javascript
driver: sessionDrivers.upstash({ ttl: 60 * 60 * 24 * 7 }),
```

### Deploy

Build the app and start the server with the two variables set in the
environment:

```shell
npm run build
node ./dist/server/entry.mjs
```

On a hosting platform, add `UPSTASH_REDIS_REST_URL` and
`UPSTASH_REDIS_REST_TOKEN` to the project's environment variables. The build
does not include them, so the server reads them when it starts.

### Next Steps

- Add rate limiting to an endpoint with [@upstash/ratelimit](/redis/sdks/ratelimit-ts/overview).
- Run durable background jobs from Astro with [Upstash Workflow](/workflow/quickstarts/astro).
