In my NextJS app, I have multiple API routes:
- /api/user/[id]
- /api/questions
- /api/posts
Each of these endpoints uses a Redis connection to get
or put
data within a Redis server.
I've noticed that I get errors in my console, because I am making too many connections to the Redis server. So I had an idea of creating a Singleton class and connecting to the Redis server once within the singleton. getInstance()
returns the connection.
But I've noticed that my singleton is created once per API route. Does NextJS do something to cause this to happen?
How can I create 1 instance of a Redis connection in a NextJS app, just for the API routes held inside of pages/api
? I'm using ioredis library.