Catalog My learning Blog
tRPC Course: Type-Safe APIs with TypeScript and React · Phase 2 · Lesson 4 · 6 min read

tRPC Context and Middleware for Authentication

On this page
  1. What context is
  2. Middleware wraps procedures
  3. Build a protected procedure
  4. Stack middleware for roles
  5. Authorization still belongs in the procedure
  6. Export a small set of base procedures
  7. Check yourself

What context is

Most procedures need something about the current request: who the user is, a database handle, a request id for logs. Passing those in as input would be wrong, since the client could fake them. Instead tRPC builds a context object on the server for every request and hands it to each procedure as ctx.

You write a createContext function. The adapter calls it once per HTTP request, and every procedure in a batch shares the result.

Shell
// src/context.ts
export type User = { id: string; name: string; role: 'member' | 'admin' };

export async function createContext(opts: { headers: Record<string, string | string[] | undefined> }) {
  const auth = opts.headers['authorization'];
  const token = typeof auth === 'string' ? auth.replace(/^Bearer /, '') : undefined;
  const user = token ? await verifyToken(token) : null;   // User | null
  return { user };
}

export type Context = Awaited<ReturnType<typeof createContext>>;

verifyToken stands for whatever your app uses: checking a JWT, looking up a session id in Redis, or reading the user from a cookie session (the BFF course does it that way). The context only says *who* is calling. It doesn't decide what they may do.

Tell tRPC the context type when you initialize it, then pass createContext to the adapter:

TypeScript
// src/trpc.ts
const t = initTRPC.context<Context>().create();

// src/server.ts
createHTTPServer({
  router: appRouter,
  createContext: ({ req }) => createContext({ headers: req.headers }),
}).listen(3000);

Keep createContext cheap. It runs on every request, including ones that only call a public health check. If something is expensive, like opening a database transaction, do it lazily inside the procedures that need it.

Middleware wraps procedures

A middleware is a function that runs before a procedure. It receives the context, can throw to stop the call, and must call next() to continue. Here's one that logs how long each call takes:

JavaScript
const timing = t.middleware(async ({ path, type, next }) => {
  const start = performance.now();
  const result = await next();
  console.log(`${type} ${path} ${result.ok ? 'ok' : 'error'} ${(performance.now() - start).toFixed(1)}ms`);
  return result;
});
// query task.list ok 0.4ms

next() returns a result object rather than throwing, so the middleware can see errors from the procedure (result.ok is false) and still return the result unchanged.

Build a protected procedure

The most common middleware checks that a user is signed in. The trick is in what it passes to next:

Shell
export const protectedProcedure = t.procedure.use(({ ctx, next }) => {
  if (!ctx.user) {
    throw new TRPCError({ code: 'UNAUTHORIZED', message: 'Sign in first' });
  }
  return next({ ctx: { user: ctx.user } });
});

Inside the if TypeScript already knows ctx.user isn't null. Passing { user: ctx.user } to next tells tRPC to carry that narrower type forward. Every procedure built on protectedProcedure sees ctx.user as User, not User | null, so nobody has to write ctx.user! or repeat the check.

Shell
export const taskRouter = router({
  mine: protectedProcedure.query(({ ctx }) => listTasksFor(ctx.user.id)), // no null check needed
});

Stack middleware for roles

Procedures are built from each other, so you can layer checks. An admin procedure starts from the protected one and adds a role check:

Shell
export const adminProcedure = protectedProcedure.use(({ ctx, next }) => {
  if (ctx.user.role !== 'admin') throw new TRPCError({ code: 'FORBIDDEN' });
  return next();
});
Each tRPC request builds a context, then passes through the middleware chain to the procedure.
Each tRPC request builds a context, then passes through the middleware chain to the procedure.

Here's what clients saw when testing these procedures:

Code
no token, me.query()            -> UNAUTHORIZED 401 "Sign in first"
member token, admin.stats()     -> FORBIDDEN 403
admin token, admin.stats()      -> { tasks: 1 }

UNAUTHORIZED means "I don't know who you are" and FORBIDDEN means "I know who you are, and the answer is no". Getting them right helps the client decide whether to show a sign-in screen or an access-denied message.

Authorization still belongs in the procedure

A role check in middleware answers "may this kind of user call this procedure at all?". It can't answer "may *this* user see *this* task?", because that depends on the input. That check goes in the procedure, or better, in the query itself:

JavaScript
byId: protectedProcedure
  .input(z.object({ id: z.string() }))
  .query(({ ctx, input }) => {
    const task = db.tasks.get(input.id);
    if (!task || task.ownerId !== ctx.user.id) {
      throw new TRPCError({ code: 'NOT_FOUND' });
    }
    return task;
  }),

Returning NOT_FOUND for someone else's task, instead of FORBIDDEN, avoids telling an attacker which ids exist. Forgetting this ownership check is one of the most common API security bugs, called broken object level authorization, and no middleware can catch it for you.

Export a small set of base procedures

A tidy trpc.ts ends up exporting a handful of building blocks:

Shell
export const router = t.router;
export const publicProcedure = t.procedure.use(timing);
export const protectedProcedure = publicProcedure.use(requireUser);
export const adminProcedure = protectedProcedure.use(requireAdmin);

Every route file picks the right one, and a code reviewer can tell at a glance which procedures are public.

TipMake protectedProcedure the default in your team's habits, and treat every publicProcedure as a decision a reviewer should notice. It's far easier to spot one public procedure that should be private than to audit a hundred.

Check yourself

Input comes from the client and can be faked. The context is built on the server from trusted sources like a verified token or a session.

It passes a narrowed context forward. Inside the middleware's if (!ctx.user) throw ... check, TypeScript knows the user exists, and handing that value to next makes tRPC carry the narrower type to every procedure built on the middleware. Those procedures can use ctx.user.id directly, with no repeated null check and no !.

An ownership check inside the procedure, comparing the task's owner with ctx.user.id. Middleware can't do it because it depends on the input and the stored data.

UNAUTHORIZED (401) means the server doesn't know who you are, so the right response is to sign in. FORBIDDEN (403) means it knows exactly who you are, and the answer is still no. The protected middleware throws the first and the admin middleware throws the second, which lets the client show a sign-in prompt or an access-denied message as appropriate.

createContext runs on every HTTP request, including public health checks and batched calls that never touch the database, so every request pays for a transaction it may not use. Keep the context cheap, such as the user and a database handle, and start transactions inside the procedures that need them.