I use Redis in my Next.js project. It works good but it seems in built time (next build
) it tries to connect to Redis and since Redis connection is not available it throws this error:
Collecting page data ..[ioredis] Unhandled error event: Error: connect ECONNREFUSED 127.0.0.1:6379
at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1495:16)
My Redis singleton client is:
import Redis from 'ioredis';
export const redis: Redis =
global.redis ||
new Redis({
host: process.env.REDIS_HOST || 'localhost',
port: Number.parseInt(process.env.REDIS_PORT ?? '6379', 10),
db: Number.parseInt(process.env.REDIS_DB ?? '6', 10),
keyPrefix: process.env.REDIS_PREFIX ?? ''
});
/** This prevents creating multiple instance of redis client in development mode */
if (process.env.NODE_ENV === 'development') {
global.redis = redis;
}
As Redis connection shouldn’t be used in build time. How can I fix this?