#software-engineering
> [!info] See more
> [Authorization | tRPC](https://trpc.io/docs/server/authorization#option-2-authorize-using-middleware)
```ts
import { initTRPC, TRPCError } from '@trpc/server';
export const t = initTRPC.context<Context>().create();
const isAuthed = t.middleware((opts) => {
const { ctx } = opts;
if (!ctx.user?.isAdmin) {
throw new TRPCError({ code: 'UNAUTHORIZED' });
}
return opts.next({
ctx: {
user: ctx.user,
},
});
});
// you can reuse this for any procedure
export const protectedProcedure = t.procedure.use(isAuthed);
t.router({
// this is accessible for everyone
hello: t.procedure
.input(z.string().nullish())
.query((opts) => `hello ${opts.input ?? opts.ctx.user?.name ?? 'world'}`),
admin: t.router({
// this is accessible only to admins
secret: protectedProcedure.query((opts) => {
return {
secret: 'sauce',
};
}),
}),
});
```