2

I'm trying to use Redis in a nextJs API which has a custom express server. I created a util file for Redis in order to connect to the Redis labs, the same way I did with mongodb. The problem is that when I try to use the client.Hset the console keeps sending me errors that econ refused, but I also made sure that when Redis is connected it console logs a string. So the console, logs both the error of econ refused, and the log connected to redis. This is how my util file looks like:

/* ------ connecting to redis ------ */
const redis = require('redis');
const { promisify } = require('util');
const client = redis.createClient({
    host: process.env.REDIS_HOSTNAME,
    port: process.env.REDIS_PORT,
    password: process.env.REDIS_PASSWORD
});
client.on('connect', ()=>{
  console.log('connected to redis')
})
/* promisifying redis in order to use async functionality */
const redisHget = promisify(client.hget).bind(client)
const redisHset = promisify(client.hset).bind(client)

module.export = {redisHget, redisHset}

It seems like every time I call the API, it reconnects to Redis. may I know if there is a way I can use redis the same way I use MongoDB by just creating and importing collections so that it doesn't keep reconnecting to the redis labs server?

1 Answer 1

5

Lee Robinson (DevRel @ Vercel), wrote a nice article about using Redis in Next.js. https://leerob.io/blog/serverless-redis-nextjs.

Complete Example here: https://github.com/vercel/next.js/blob/canary/examples/with-redis/README.md

Snippets:

# env.local
REDIS_URL=redis://:password@endpoint:port

We'll use ioredis, a Node.js Redis client with async/await support, to connect to Redis.

// lib/redis.js
import Redis from 'ioredis';

const redis = new Redis(process.env.REDIS_URL);

export default redis;

Using it, either in pages/ or pages/api/,

import redis from '@/lib/redis';

const value = JSON.parse(await redis.hget('feedback', id));
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.