2

I am using iron-session to handle the sessions on my nextjs app, but some of the sessions were too big so I created only a key with the iron-session and getting the result using Redis.

I have a really basic connector

import { createClient } from 'redis';
import { logError } from './logger';

const client = createClient({ url: process.env.REDIS_URL });

client.on('error', (error) => {
    logError(error)
});

export async function connect() {
    if (!client.isOpen) await client.connect()
    return client
}

But I have a lot Socket closed unexpectedly error, should be because I am never calling the quit function.

I do not know if this is a big issue for the Redis server to have this kind of error all the time, if not, I could just ignore this it. The other solution would be to call quit at the end of each my api and getServerSideProps which are using sessions from Redis, but I do not find it spotless, it will be a lot of code and complexity

Ajouve
  • 9,735
  • 26
  • 90
  • 137
  • Where is the program been run on? Could you elaborate runtime environment and is it serverless? Maybe its only invoked when called. How about reestablishing connection (retry connectivity) upon connection loss? – Abhigyan Tiwari Oct 31 '22 at 08:57
  • This is because your redis connection is trying to connect in client side as well. Client side does not support redis connections, you have to initialize/connect to the redis only in the server side. – Dulaj Ariyaratne Oct 31 '22 at 16:36
  • Redis is onli call on API routes not on client side – Ajouve Oct 31 '22 at 18:19
  • Does this answer your question: [Node.js: Closing all Redis clients on shutdown](https://stackoverflow.com/questions/20895063/node-js-closing-all-redis-clients-on-shutdown)? – juliomalves Nov 02 '22 at 19:20
  • @juliomalves thanks but `SIGINT` and `SIGTERM` are not called – Ajouve Nov 08 '22 at 09:45

1 Answers1

-1

You should make sure to execute client.connect() after client.on('error')

From the code you have, it has potential client.connect() called without client.on('error') to be registered first. You can see this thread about handling error.

https://github.com/redis/node-redis/issues/1985#issuecomment-1116865925