---
hide_table_of_contents: true
---

import CodeBlock from "@theme/CodeBlock";

# Upstash Redis-Backed Chat Memory

Because Upstash Redis works via a REST API, you can use this with [Vercel Edge](https://vercel.com/docs/concepts/functions/edge-functions/edge-runtime), [Cloudflare Workers](https://developers.cloudflare.com/workers/) and other Serverless environments.
Based on Redis-Backed Chat Memory.

For longer-term persistence across chat sessions, you can swap out the default in-memory `chatHistory` that backs chat memory classes like `BufferMemory` for an Upstash [Redis](https://redis.io/) instance.

## Setup

You will need to install [@upstash/redis](https://github.com/upstash/upstash-redis) in your project:

```bash npm2yarn
npm install @upstash/redis
```

You will also need an Upstash Account and a Redis database to connect to. See instructions on [Upstash Docs](https://docs.upstash.com/redis) on how to create a HTTP client.

## Usage

Each chat history session stored in Redis must have a unique id. You can provide an optional `sessionTTL` to make sessions expire after a give number of seconds.
The `config` parameter is passed directly into the `new Redis()` constructor of [@upstash/redis](https://docs.upstash.com/redis/sdks/javascriptsdk/overview), and takes all the same arguments.

import Example from "@examples/memory/upstash_redis.ts";

<CodeBlock language="typescript">{Example}</CodeBlock>

## Advanced Usage

You can also directly pass in a previously created [@upstash/redis](https://docs.upstash.com/redis/sdks/javascriptsdk/overview) client instance:

import AdvancedExample from "@examples/memory/upstash_redis_advanced.ts";

<CodeBlock language="typescript">{AdvancedExample}</CodeBlock>
