Skip to main content

Bun Redis with Upstash

还没翻译译自英文(bun.com)本页 12 段都还没译

Upstash is a fully managed Redis database as a service. It works with the Redis® API, so you can connect with Bun's native Redis client.

Note

TLS is enabled by default for all Upstash Redis databases.


  1. Create a new project

    Create a new project with bun init:

    bun init bun-upstash-redis
    cd bun-upstash-redis
  2. Create an Upstash Redis database

    Go to the Upstash dashboard and create a new Redis database. After completing the getting started guide, you'll see your database page with connection information.

    The database page displays two connection methods: HTTP and TLS. For Bun's Redis client, you need the TLS connection details; the URL starts with rediss://.

    Upstash Redis database page

  3. Connect using Bun's Redis client

    Set the REDIS_URL environment variable in your .env file using the Redis endpoint (not the REST URL):

    REDIS_URL=rediss://********@********.upstash.io:6379

    Bun's Redis client reads connection information from REDIS_URL by default:

    import { redis } from "bun";
    
    // Reads from process.env.REDIS_URL automatically
    await redis.set("counter", "0");

    Alternatively, create a custom client with RedisClient:

    import { RedisClient } from "bun";
    
    const redis = new RedisClient(process.env.REDIS_URL);
  4. Use the Redis client

    Use the Redis client to read and write keys in your Upstash database:

    import { redis } from "bun";
    
    // Get a value
    let counter = await redis.get("counter");
    
    // Set a value if it doesn't exist
    if (!counter) {
    	await redis.set("counter", "0");
    }
    
    // Increment the counter
    await redis.incr("counter");
    
    // Get the updated value
    counter = await redis.get("counter");
    console.log(counter);
    1

    The Redis client handles connections automatically. You don't need to connect or disconnect manually for basic operations.

译文 © 2026 fanyi.dev · 原文 © 2026 the Bun project (LICENSE.md names no copyright holder) (MIT)