Protected routes require user authentication and are used for endpoints that should only be accessible to logged-in users.
import { router, protectedProcedure } from '../lib/trpc'; import { z } from 'zod'; export const yourRouter = router({ // Your protected route yourProtectedRoute: protectedProcedure .input(z.object({ yourInput: z.string(), yourInput2: z.string(), })) .mutation(async ({ ctx, input }) => { // Your logic here return { success: true }; }), });
import { router, protectedProcedure } from '../lib/trpc'; import { z } from 'zod'; export const userRouter = router({ // Get user profile getProfile: protectedProcedure.query(async ({ ctx }) => { return ctx.session.user; }), // Update user settings updateSettings: protectedProcedure .input(z.object({ theme: z.enum(['light', 'dark']), notifications: z.boolean(), })) .mutation(async ({ ctx, input }) => { // Update user settings in database return { success: true }; }), });
export const protectedProcedure = t.procedure.use(({ ctx, next }) => { if (!ctx.session) { throw new TRPCError({ code: 'UNAUTHORIZED', message: 'Authentication required', }); } return next(); });
// apps/server/src/routers/profile.ts import { router, protectedProcedure } from '../lib/trpc'; import { z } from 'zod'; export const profileRouter = router({ // Get user profile getProfile: protectedProcedure.query(async ({ ctx }) => { const user = await prisma.user.findUnique({ where: { id: ctx.session.userId }, }); return user; }), // Update profile updateProfile: protectedProcedure .input(z.object({ name: z.string().optional(), email: z.string().email().optional(), bio: z.string().optional(), })) .mutation(async ({ ctx, input }) => { const updated = await prisma.user.update({ where: { id: ctx.session.userId }, data: input, }); return updated; }), });
// In your React component function ProfileComponent() { const { data: profile, isLoading } = trpc.getProfile.useQuery(); const updateProfile = trpc.profileRouter.updateProfile.useMutation(); const handleUpdate = async (data) => { try { await updateProfile.mutateAsync(data); } catch (error) { console.error('Error updating profile:', error); } }; return ( <div> {isLoading ? 'Loading...' : ( <form onSubmit={handleUpdate}> {/* Profile form fields */} </form> )} </div> ); }