I'm trying to store state in the tRPC context between different procedures called by the same user. I use websockets/wsLink, so context is created once when the user first connects. This context mutation should only happen when a user calls a specific procedure.
However, It looks like the context properties are reset whenever a procedure is called by the user.
However, mutating properties of properties works to share state between procedures.
I followed the code and found that it's a limitation caused by spreading:
ctx:
nextOpts && 'ctx' in nextOpts
? { ...callOpts.ctx, ...nextOpts.ctx }
: callOpts.ctx,
It's an implementation detail of tRPC, where 2 contexts are merged together to support middlewares adding properties to the context.
My recommendation would be avoid changing properties on context directly, because you would be editing a temporarily generated context for the last middleware called. If you edit anything inside specific properties, these will exist because these were just copied from the original context.