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​
tsx
// -------------------------------------------------// @filename: context.ts// -------------------------------------------------import {inferAsyncReturnType } from '@trpc/server';import * astrpcNext from '@trpc/server/adapters/next';import {getSession } from 'next-auth/react';Â/*** Creates context for an incoming request* @link https://trpc.io/docs/context*/export async functioncreateContext (opts :trpcNext .CreateNextContextOptions ) {constsession = awaitgetSession ({req :opts .req });return {session ,};};Âexport typeContext =inferAsyncReturnType <typeofcreateContext >;Â// -------------------------------------------------// @filename: trpc.ts// -------------------------------------------------import {initTRPC ,TRPCError } from '@trpc/server';import {Context } from './context';Âconstt =initTRPC .context <Context >().create ();ÂÂconstisAuthed =t .middleware (({next ,ctx }) => {if (!ctx .session ?.user ?.throw newTRPCError ({code : 'UNAUTHORIZED',});}returnnext ({ctx : {// Infers the `session` as non-nullablesession :ctx .session ,},});});Âexport constmiddleware =t .middleware ;export constrouter =t .router ;Â/*** Unprotected procedure**/export constpublicProcedure =t .procedure ;Â/*** Protected procedure**/export constprotectedProcedure =t .procedure .use (isAuthed );
tsx
// -------------------------------------------------// @filename: context.ts// -------------------------------------------------import {inferAsyncReturnType } from '@trpc/server';import * astrpcNext from '@trpc/server/adapters/next';import {getSession } from 'next-auth/react';Â/*** Creates context for an incoming request* @link https://trpc.io/docs/context*/export async functioncreateContext (opts :trpcNext .CreateNextContextOptions ) {constsession = awaitgetSession ({req :opts .req });return {session ,};};Âexport typeContext =inferAsyncReturnType <typeofcreateContext >;Â// -------------------------------------------------// @filename: trpc.ts// -------------------------------------------------import {initTRPC ,TRPCError } from '@trpc/server';import {Context } from './context';Âconstt =initTRPC .context <Context >().create ();ÂÂconstisAuthed =t .middleware (({next ,ctx }) => {if (!ctx .session ?.user ?.throw newTRPCError ({code : 'UNAUTHORIZED',});}returnnext ({ctx : {// Infers the `session` as non-nullablesession :ctx .session ,},});});Âexport constmiddleware =t .middleware ;export constrouter =t .router ;Â/*** Unprotected procedure**/export constpublicProcedure =t .procedure ;Â/*** Protected procedure**/export constprotectedProcedure =t .procedure .use (isAuthed );