Request-scoped DI containers in App Router / RSC #95092
Replies: 2 comments 1 reply
-
|
Your approach looks broadly aligned with how App Router and RSC are intended to work. Using react.cache() as the mechanism for creating a request-scoped container is a sensible choice because it provides request-local memoization and allows nested Server Components to share the same container during a render. |
Beta Was this translation helpful? Give feedback.
-
|
This is basically the right shape. Two things I'd flag before you lean on it too hard:
The "only pass serializable snapshots to the client" rule is the right call and honestly the part people get wrong most, so good that it's baked in from the start. |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
-
Hi! I’m experimenting with a small TypeScript dependency injection library and recently added a Next.js App Router / RSC adapter.
Library:
https://www.npmjs.com/package/di-craft
https://github.com/bezmen-e/di-craft
Next.js App Router docs section:
https://github.com/bezmen-e/di-craft#nextjs-app-router
The idea is to keep the core DI container framework-agnostic and expose Next-specific behavior through separate subpath exports.
The model is:
React.cacheas the request memoization primitive for RSC;So instead of this:
it uses this:
The adapter also has an explicit helper for Route Handlers and Server Actions, where the request container can be disposed after the callback.
I prepared a small App Router demo that covers:
Demo source:
https://github.com/bezmen-e/di-craft-next-demo
Demo README:
https://github.com/bezmen-e/di-craft-next-demo#readme
Note: this demo is designed for a real local Node.js environment or Vercel deployment. StackBlitz/WebContainer environments may fail with current Next.js dev runtime limitations around Turbopack/Webpack fallback and RSC internals.
A few things I’m trying to validate:
React.cachethe right primitive for request-scoped userland containers in RSC?server state -> serializable snapshot -> client statemodel fit App Router boundaries well?This is not a request for framework integration. I’m mostly trying to validate whether this userland pattern is aligned with Next.js/RSC semantics.
I’d be happy to hear any feedback, corrections, or advice on this approach, especially around request lifecycle, disposal, and state snapshots in App Router/RSC.
Beta Was this translation helpful? Give feedback.
All reactions