Next.js with Redis
This tutorial uses Redis as state store for a Next.js application. We simply add a counter that pulls the data from Redis.
Step-1: Create Next.js Project
npx create-next-app nextjs-with-redis
Step-2: Create a Redis (Upstash) Database
- Create a database as getting started.
- Install Redis client (ioredis) via
npm install ioredis
Step-3: Update the Next.js App
- Copy the url in the database page Upstash console.
- Update the
index.js
as below:
import Head from 'next/head'
import styles from '../styles/Home.module.css'
import Redis from 'ioredis'
export default function Home({ data }) {
return (
<div className={styles.container}>
<Head>
<title>Create Next App</title>
<link rel="icon" href="/favicon.ico" />
</Head>
<main className={styles.main}>
<h1 className={styles.title}>
Welcome to <a href="https://nextjs.org">Next.js! </a>
</h1>
<p className={styles.description}>
Get started by editing{' '}
<code className={styles.code}>pages/index.js</code>
</p>
<p className={styles.description}>
View Count:{' '}
<code className={styles.title}>{data}</code>
</p>
</main>
<footer className={styles.footer}>
<a
href="https://vercel.com?utm_source=create-next-app&utm_medium=default-template&utm_campaign=create-next-app"
target="_blank"
rel="noopener noreferrer"
>
Powered by{' '}
<img src="/vercel.svg" alt="Vercel Logo" className={styles.logo} />
</a>
</footer>
</div>
)
}
export async function getServerSideProps() {
let redis = new Redis("YOUR_REDIS_ENDPOINT");
const data = await redis.incr("counter");
redis.quit()
return { props: { data } }
}
Step-4: Run the app
npm run dev
Notes:
- For best performance the application should run in the same region with the Redis database's region.
- Alternatively, counter can be read from the APIs instead of getServerSideProps().