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

server/context.ts

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