Project Setup

We will create a new Next.js application and install the redis package.

npx create-next-app@latest --experimental-app my-app
cd my-app
npm install @upstash/redis

The Code

Update /app/page.tsx with the following code:

import { Redis } from "@upstash/redis";
import styles from "./page.module.css";

const redis = Redis.fromEnv();

export const revalidate = 0; // disable cache

export default async function Home() {
  const member = await redis.srandmember<string>("nextjs13");

  return (
    <div className={styles.container}>
      <main className={styles.main}>
        <h1 className={styles.title}>Welcome {member}</h1>
        <p className={styles.description}>
          You have been randomly chosen by the redis algorithm.

Redis.fromEnv() automatically loads UPSTASH_REDIS_REST_URL and UPSTASH_REDIS_REST_TOKEN from the environment variables. We’ll set them later.

Database Setup

Create a Redis database using Upstash Console or Upstash CLI and copy the UPSTASH_REDIS_REST_URL and UPSTASH_REDIS_REST_TOKEN into your .env file.

Let’s quickly add some data to redis. Go to the CLI tab and run the following commands

sadd nextjs13 Walter
sadd nextjs13 Jesse
sadd nextjs13 Saul

Run & Deploy

You can run the app locally: npm run dev and check http://localhost:3000/

Deploy your app with npx vercel

You can also integrate your Vercel projects with Upstash using Vercel Integration module. Check this article.