This tutorial uses Redis as state store for a Nuxt application. In it, we will build an application which simply increments a counter and saves & fetches the last increment time.

See code and demo

1 Create Nuxt.js Project

Run this in terminal

npx nuxi@latest init nuxtjs-with-redis

Go to the new directory nuxtjs-with-redis and install @upstash/redis:

npm install @upstash/redis

2 Create a Upstash Redis database

Next, you will need an Upstash Redis database. You can follow our guide for creating a new database.

3 Set up environment variables

Copy the .env.example file in this directory to .env

cp .env.example .env

Then, set the following environment variables:

UPSTASH_REDIS_REST_URL=""
UPSTASH_REDIS_REST_TOKEN=""

You can get the values of these env variables on the page of your Redis database.

4 Define the endpoint

Next, we will define the endpoint which will call Redis:

title="server/api/increment.ts"
import { defineEventHandler } from "h3";
import { Redis } from "@upstash/redis";

// Initialize Redis
const redis = new Redis({
  url: process.env.UPSTASH_REDIS_REST_URL || "",
  token: process.env.UPSTASH_REDIS_REST_TOKEN || ""
});

export default defineEventHandler(async () => {
  const identifier = "api_call_counter";

  try {
    // Increment the API call counter and get the updated value
    const count = await redis.incr(identifier);

    // Optionally, you can also retrieve other information like the last time it was called
    const lastCalled = await redis.get("last_called");
    const lastCalledAt = lastCalled || "Never";

    // Store the current timestamp as the last called time
    await redis.set("last_called", new Date().toISOString());

    // Return the count and last called time
    return {
      success: true,
      count: count,
      lastCalled: lastCalledAt,
    };
  } catch (error) {
    console.error("Redis error:", error);
    return {
      success: false,
      message: "Error interacting with Redis",
    };
  }
});

5 Run

Finally, we can run the application and call our endpoint:

npm run dev

If you are using our example app, you can simply click the Increment button to run the endpoint we defined.

Otherwise, you can simply make a curl request:

curl http://localhost:3000/api/increment

When you make the request, you should see something like this:

{
  "success": true,
  "count": 166,
  "lastCalled": "2024-10-10T07:04:42.381Z"
}

Notes:

  • For best performance the application should run in the same region with the Redis database’s region.