Request Context

The createContext() function is called for each request and the result is propagated to all resolvers. You can use this to pass contextual data down to the resolvers.

Example code

  1. // The app's context - is generated for each incoming request
  2. export async function createContext(opts?: trpcNext.CreateNextContextOptions) {
  3. // Create your context based on the request object
  4. // Will be available as `ctx` in all your resolvers
  5. // This is just an example of something you'd might want to do in your ctx fn
  6. async function getUserFromHeader() {
  7. if (opts?.req.headers.authorization) {
  8. // const user = await decodeJwtToken(req.headers.authorization.split(' ')[1])
  9. // return user;
  10. }
  11. return null;
  12. }
  13. const user = await getUserFromHeader();
  14. return {
  15. user,
  16. };
  17. }
  18. type Context = inferAsyncReturnType<typeof createContext>;
  19. // Helper function to create a router with your app's context
  20. export function createRouter() {
  21. return trpc.router<Context>();
  22. }