// Redis is a Node.js specific library that can't run in the browser// Trying to use it in code that runs on both Node.js and the browser will result in a module not found error for modules that ioredis relies on// If you run into such an error it's recommended to move the code to `getStaticProps` or `getServerSideProps` as those methods guarantee that the code is only run in Node.js.import redis from'../lib/redis'import { useEffect, useState } from'react'exportdefaultfunctionHome() {const [message,setMessage] =useState()useEffect(() => {redis.get('message').then((result) => {setMessage(result) }, [])return <h1>{message}</h1>
Example of code that would break:
lib/redis.js
import Redis from'ioredis'// Modules that hold Node.js-only code can't also export React components// Tree shaking of getStaticProps/getStaticPaths/getServerSideProps is ran only on page filesconstredis=newRedis(process.env.REDIS_URL)exportfunctionMyComponent() {return <h1>Hello</h1>exportdefault redis
pages/index.js
// In practice you'll want to refactor the `MyComponent` to be a separate file so that tree shaking ensures that specific import is not included for the browser compilationimport redis, { MyComponent } from'../lib/redis'exportasyncfunctiongetStaticProps() {constmessage=awaitredis.get('message')return { message,