I have a NextJS app which has API routes inside of pages/api
. Each route reads from a Singleton, which holds 1 instance of a Redis server connection (ioredis) – so I can reuse 1 connection and not connect multiple times.
I’ve noticed that when I use these routes, the Singleton is recreated once per route. I can see that NextJS is compiling these at runtime, which makes me think that a new instance of the Singleton is being created for each route – that’s causing multiple instances of the Redis connection:
event - compiled client and server successfully in 174 ms (1201 modules)
wait - compiling /api/rtmtoken...
event - compiled client and server successfully in 106 ms (1202 modules)
wait - compiling /api/users...
event - compiled client and server successfully in 113 ms (1203 modules)
How do I turn off the compiling at runtime here? Alternatively, is there a better practice for holding 1 instance of a connection to Redis or similar?
Thanks!