Skip to main content

Nuxt.js with Redis

This tutorial uses Redis as state store for a Nuxt.js application. We simply increment a counter that pulls the data from Redis.

See code and demo

1 Create Nuxt.js Project#

Run this in terminal

yarn create nuxt-app nuxtjs-with-redis

2 Set up environment variables#

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

cp .env.local.example .env.local
  • REDIS_URL: Copy the url in the database page of the Upstash console

This example uses ioredis, you can copy the connection string from the Node tab in the console.

3 Server Middleware#

We will write a Nuxt middleware which increments a counter in Redis and returns its new value.

import Redis from "ioredis"
export default async function (req, res) {  const redis = new Redis(process.env.REDIS_URL)  const count = await redis.incr("counter")  redis.quit()
  res.setHeader("Content-Type", "application/json")  res.write(JSON.stringify({ count }))  res.end()}

Now we will configure the middleware in nuxt.config.js

export default {  head: { title: "nuxt-with-redis" },  buildModules: ["@nuxtjs/tailwindcss"],  serverMiddleware: [{ path: "/api/count", handler: "~/api/count.js" }]}

4 Run#

yarn dev

Go to http://localhost:3000/


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