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 );