Skip to content

Connect, collaborate, and grow with a community of TypeScript developers

feat(web): migrate notifications to tRPC (incremental server-action migration) (#1774)

bautistaaa525948bf1c9b
diff --git a/apps/web/package.json b/apps/web/package.json
index a3133c57..3638aa42 100644
--- a/apps/web/package.json
+++ b/apps/web/package.json
@@ -40,6 +40,9 @@
"@tanstack/react-query": "5.101.2",
"@tanstack/react-query-devtools": "5.101.2",
"@tanstack/react-table": "^8.20.5",
+ "@trpc/client": "11.18.0",
+ "@trpc/server": "11.18.0",
+ "@trpc/tanstack-react-query": "11.18.0",
"@uiw/react-md-editor": "^4.0.4",
"@uploadthing/react": "^6.8.0",
"@vercel/analytics": "^1.1.1",
diff --git a/apps/web/src/app/api/trpc/[trpc]/route.ts b/apps/web/src/app/api/trpc/[trpc]/route.ts
new file mode 100644
index 00000000..e88d58c0
--- /dev/null
+++ b/apps/web/src/app/api/trpc/[trpc]/route.ts
@@ -0,0 +1,31 @@
+import { fetchRequestHandler } from '@trpc/server/adapters/fetch';
+import { type NextRequest } from 'next/server';
+
+import { appRouter } from '~/server/api/root';
+import { createTRPCContext } from '~/server/api/trpc';
+
+/**
+ * This wraps the `createTRPCContext` helper and provides the required context for the tRPC API when
+ * handling a HTTP request (e.g. when you make requests from Client Components).
+ */
+const createContext = async (req: NextRequest) => {
+ return createTRPCContext({
+ headers: req.headers,
+ });
+};
+
+const handler = (req: NextRequest) =>
+ fetchRequestHandler({
+ endpoint: '/api/trpc',
+ req,
+ router: appRouter,
+ createContext: () => createContext(req),
+ onError:
+ process.env.NODE_ENV === 'development'
+ ? ({ path, error }) => {
+ console.error(`❌ tRPC failed on ${path ?? '<no-path>'}: ${error.message}`);
+ }
+ : undefined,
+ });
+
+export { handler as GET, handler as POST };
diff --git a/apps/web/src/app/notifications/notfication-item.tsx b/apps/web/src/app/notifications/notfication-item.tsx
index 8753e839..6ff8c211 100644
--- a/apps/web/src/app/notifications/notfication-item.tsx
+++ b/apps/web/src/app/notifications/notfication-item.tsx
@@ -9,7 +9,10 @@ import Link from 'next/link';
import { useRouter } from 'next/navigation';
import { useInView } from 'react-intersection-observer';
import { getRelativeTime } from '~/utils/relativeTime';
-import type { Notification } from './notification.actions';
+import type { RouterOutputs } from '~/trpc/types';
+
+export type Notification =
+ RouterOutputs['notification']['getNotifications']['notifications'][number];
const BLURBS = {
MENTION: 'mentioned you in a comment',
diff --git a/apps/web/src/app/notifications/notification-page.tsx b/apps/web/src/app/notifications/notification-page.tsx
index 772433c4..62cb1a67 100644
--- a/apps/web/src/app/notifications/notification-page.tsx
+++ b/apps/web/src/app/notifications/notification-page.tsx
@@ -7,8 +7,7 @@ import { useToast } from '@repo/ui/components/use-toast';
import { Bell } from '@repo/ui/icons';
import { useMutation, useQueryClient } from '@tanstack/react-query';
import { useRef } from 'react';
-import { NOTIFICATION_QUERY_KEY } from '~/components/Navigation/notification-link';
-import { markAllAsRead, markNotificationsAsRead } from './notification.actions';
+import { useTRPC } from '~/trpc/react';
import { NotificationsAll } from './notifications-all';
import { NotificationsMentions } from './notifications-mentions';
@@ -16,10 +15,10 @@ export default function NotificationPage() {
const seenNotifications = useRef(new Set<number>());
const timeoutRef = useRef<number>(undefined);
const { toast } = useToast();
+ const trpc = useTRPC();
const client = useQueryClient();
- const mutation = useMutation({
- mutationFn: markNotificationsAsRead,
- });
+ const markAsReadMutation = useMutation(trpc.notification.markAsRead.mutationOptions());
+ const markAllAsReadMutation = useMutation(trpc.notification.markAllAsRead.mutationOptions());
const onSeen = (id: number) => {
seenNotifications.current.add(id);
@@ -29,24 +28,25 @@ export default function NotificationPage() {
timeoutRef.current = window.setTimeout(() => {
timeoutRef.current = undefined;
- mutation.mutate(Array.from(seenNotifications.current), {
- onSuccess: () => {
- for (const id of copy) {
- seenNotifications.current.delete(id);
- }
+ markAsReadMutation.mutate(
+ { ids: Array.from(seenNotifications.current) },
+ {
+ onSuccess: () => {
+ for (const id of copy) {
+ seenNotifications.current.delete(id);
+ }
+ },
},
- });
- client.setQueryData([NOTIFICATION_QUERY_KEY], 0);
+ );
+ client.setQueryData(trpc.notification.getUnreadCount.queryKey(), 0);
}, 500);
};
const onMarkAllAsReadClick = async () => {
- await markAllAsRead();
- // partial matching is not working for some reason
- await client.invalidateQueries({ queryKey: ['notifications-all'] });
- await client.invalidateQueries({ queryKey: ['notifications-mentions'] });
- await client.refetchQueries({ queryKey: ['notifications-all'] });
- await client.refetchQueries({ queryKey: ['notifications-mentions'] });
+ await markAllAsReadMutation.mutateAsync();
+ // invalidate + refetch every notification query (all, mentions, unread count)
+ await client.invalidateQueries(trpc.notification.pathFilter());
+ await client.refetchQueries(trpc.notification.getNotifications.infiniteQueryFilter());
toast({
variant: 'success',
title: 'All notifications marked as read.',
diff --git a/apps/web/src/app/notifications/notification.actions.ts b/apps/web/src/app/notifications/notification.actions.ts
deleted file mode 100644
index b0cb62d3..00000000
--- a/apps/web/src/app/notifications/notification.actions.ts
+++ /dev/null
@@ -1,140 +0,0 @@
-'use server';
-
-import { prisma } from '@repo/db';
-import { headers } from 'next/headers';
-import { auth } from '~/server/auth';
-import { rateLimit } from '~/utils/rateLimit';
-
-export async function markNotificationsAsRead(ids: number[]) {
- const session = await auth();
-
- if (!session) {
- throw new Error('User not authenticated');
- }
-
- await prisma.notification.updateMany({
- where: {
- toUserId: session.user.id,
- id: {
- in: ids,
- },
- },
- data: {
- isRead: true,
- },
- });
-}
-
-export type Notification = Awaited<ReturnType<typeof getNotifications>>['notifications'][0];
-export type GetNotificationsResponse = Awaited<ReturnType<typeof getNotifications>>;
-
-/**
- * Fetches user enrolled tracks based on current session.
- */
-export async function getNotifications({
- cursor,
- mentionsOnly = false,
-}: {
- cursor?: number;
- mentionsOnly?: boolean;
-}) {
- const session = await auth();
- if (!session) {
- throw new Error('not authenticated');
- }
-
- const notifications = await prisma.notification.findMany({
- take: 50,
- skip: cursor ? 1 : 0,
- cursor: cursor ? { id: cursor } : undefined,
- where: {
- toUserId: session.user.id,
- type: mentionsOnly ? 'MENTION' : undefined,
- },
- select: {
- id: true,
- blurb: true,
- createdAt: true,
- url: true,
- comment: {
- select: {
- id: true,
- rootType: true,
- text: true,
- },
- },
- isRead: true,
- content: true,
- fromUser: {
- select: {
- image: true,
- name: true,
- },
- },
- type: true,
- },
- orderBy: [
- {
- createdAt: 'desc',
- },
- {
- id: 'desc',
- },
- ],
- });
-
- if (notifications.length === 0) {
- return {
- notifications: [],
- cursor: undefined,
- };
- }
-
- const nextPage = await prisma.notification.findMany({
- take: 1,
- skip: 1,
- cursor: { id: notifications.at(-1)?.id },
- where: {
- toUserId: session.user.id,
- type: mentionsOnly ? 'MENTION' : undefined,
- },
- select: {
- id: true,
- },
- orderBy: [
- {
- createdAt: 'desc',
- },
- {
- id: 'desc',
- },
- ],
- });
-
- return {
- notifications,
- cursor: nextPage.length > 0 ? notifications.at(-1)?.id : undefined,
- };
-}
-
-export async function markAllAsRead() {
- const ip = (await headers()).get('x-forwarded-for') ?? 'unknown';
- const isRateLimited = rateLimit(ip);
- if (isRateLimited) {
- throw new Error('Rate limit exceeded');
- }
-
- const session = await auth();
- if (!session) {
- throw new Error('not authenticated');
- }
-
- await prisma.notification.updateMany({
- where: {
- toUserId: session.user.id ?? '',
- },
- data: {
- isRead: true,
- },
- });
-}
diff --git a/apps/web/src/app/notifications/notifications-all.tsx b/apps/web/src/app/notifications/notifications-all.tsx
index 3b079e27..7bc49125 100644
--- a/apps/web/src/app/notifications/notifications-all.tsx
+++ b/apps/web/src/app/notifications/notifications-all.tsx
@@ -3,21 +3,21 @@
import { useInfiniteQuery } from '@tanstack/react-query';
import { Fragment } from 'react';
import InfiniteList from '~/components/infinite-list';
+import { useTRPC } from '~/trpc/react';
import { Empty } from './empty';
import { NotificationItem } from './notfication-item';
-import { getNotifications } from './notification.actions';
export function NotificationsAll({ onSeen }: { onSeen: (v: number) => void }) {
- const { data, fetchNextPage, isLoading, isFetchingNextPage, hasNextPage } = useInfiniteQuery({
- initialPageParam: 0,
- queryKey: ['notifications-all'],
- queryFn: ({ pageParam }) => {
- return getNotifications({ cursor: pageParam });
- },
- getNextPageParam: (lastPage) => {
- return lastPage?.cursor;
- },
- });
+ const trpc = useTRPC();
+ const { data, fetchNextPage, isLoading, isFetchingNextPage, hasNextPage } = useInfiniteQuery(
+ trpc.notification.getNotifications.infiniteQueryOptions(
+ {},
+ {
+ initialCursor: 0,
+ getNextPageParam: (lastPage) => lastPage?.cursor,
+ },
+ ),
+ );
if (isLoading) {
return null;
diff --git a/apps/web/src/app/notifications/notifications-mentions.tsx b/apps/web/src/app/notifications/notifications-mentions.tsx
index efd92eeb..59ce9a4f 100644
--- a/apps/web/src/app/notifications/notifications-mentions.tsx
+++ b/apps/web/src/app/notifications/notifications-mentions.tsx
@@ -3,19 +3,21 @@
import { useInfiniteQuery } from '@tanstack/react-query';
import { Fragment } from 'react';
import InfiniteList from '~/components/infinite-list';
+import { useTRPC } from '~/trpc/react';
import { Empty } from './empty';
import { NotificationItem } from './notfication-item';
-import { getNotifications } from './notification.actions';
export function NotificationsMentions({ onSeen }: { onSeen: (v: number) => void }) {
- const { data, fetchNextPage, isLoading, isFetchingNextPage, hasNextPage } = useInfiniteQuery({
- initialPageParam: 0,
- queryKey: ['notifications-mentions'],
- queryFn: ({ pageParam }) => {
- return getNotifications({ cursor: pageParam, mentionsOnly: true });
- },
- getNextPageParam: (lastPage) => lastPage?.cursor,
- });
+ const trpc = useTRPC();
+ const { data, fetchNextPage, isLoading, isFetchingNextPage, hasNextPage } = useInfiniteQuery(
+ trpc.notification.getNotifications.infiniteQueryOptions(
+ { mentionsOnly: true },
+ {
+ initialCursor: 0,
+ getNextPageParam: (lastPage) => lastPage?.cursor,
+ },
+ ),
+ );
if (isLoading) {
return null;
diff --git a/apps/web/src/app/providers.tsx b/apps/web/src/app/providers.tsx
index 4bf48077..7f569652 100644
--- a/apps/web/src/app/providers.tsx
+++ b/apps/web/src/app/providers.tsx
@@ -2,11 +2,10 @@
import { SessionProvider } from '@repo/auth/react';
import { TooltipProvider } from '@repo/ui/components/tooltip';
-import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
-import { ReactQueryDevtools } from '@tanstack/react-query-devtools';
import { ThemeProvider } from 'next-themes';
-import React, { Suspense } from 'react';
+import { Suspense } from 'react';
import { Toolbar } from '~/components/toolbar';
+import { TRPCReactProvider } from '~/trpc/react';
import { FeatureFlagProvider } from './feature-flag-provider';
interface ProvidersProps {
@@ -14,21 +13,8 @@ interface ProvidersProps {
}
export function Providers({ children }: ProvidersProps) {
- const [queryClient] = React.useState(
- () =>
- new QueryClient({
- defaultOptions: {
- queries: {
- // With SSR, we usually want to set some default staleTime
- // above 0 to avoid refetching immediately on the client
- staleTime: 5000,
- },
- },
- }),
- );
return (
- <QueryClientProvider client={queryClient}>
- <ReactQueryDevtools initialIsOpen={false} buttonPosition="bottom-right" />
+ <TRPCReactProvider>
<SessionProvider>
<ThemeProvider attribute="class" enableSystem disableTransitionOnChange>
<FeatureFlagProvider>
@@ -39,6 +25,6 @@ export function Providers({ children }: ProvidersProps) {
</Suspense>
</ThemeProvider>
</SessionProvider>
- </QueryClientProvider>
+ </TRPCReactProvider>
);
}
diff --git a/apps/web/src/components/Navigation/index.tsx b/apps/web/src/components/Navigation/index.tsx
index 652b8194..14cb33e8 100644
--- a/apps/web/src/components/Navigation/index.tsx
+++ b/apps/web/src/components/Navigation/index.tsx
@@ -13,12 +13,12 @@ import { Suspense } from 'react';
import { auth } from '~/server/auth';
import { isAdmin, isAdminOrModerator } from '~/utils/auth-guards';
import { getAllFlags } from '~/utils/feature-flags';
+import { api } from '~/trpc/server';
import { Search } from '../search/search';
import { LoginLink } from './login-link';
import { MobileNav } from './mobile-nav';
import { NavLink } from './nav-link';
import { NavWrapper } from './nav-wrapper';
-import { getNotificationCount } from './navigation.actions';
import { NotificationLink } from './notification-link';
import { SignOutLink } from './signout-link';
import { SkipToCodeEditor } from './skip-to-code-editor';
@@ -36,11 +36,12 @@ export function getAdminUrl() {
}
export async function Navigation() {
- const [session, featureFlags, notificationCount] = await Promise.all([
- auth(),
- getAllFlags(),
- getNotificationCount(),
- ]);
+ const [session, featureFlags] = await Promise.all([auth(), getAllFlags()]);
+ // The unread badge only renders for authenticated users, and `getUnreadCount`
+ // is a protected procedure, so skip the call entirely when logged out. For
+ // authenticated users we intentionally let real DB/tRPC errors surface instead
+ // of masking them as a zero count.
+ const notificationCount = session ? await api.notification.getUnreadCount() : 0;
const isAdminOrMod = isAdminOrModerator(session);
const isAdminRole = isAdmin(session);
diff --git a/apps/web/src/components/Navigation/navigation.actions.ts b/apps/web/src/components/Navigation/navigation.actions.ts
deleted file mode 100644
index 651eacc7..00000000
--- a/apps/web/src/components/Navigation/navigation.actions.ts
+++ /dev/null
@@ -1,15 +0,0 @@
-'use server';
-
-import { prisma } from '@repo/db';
-import { auth } from '~/server/auth';
-
-export async function getNotificationCount() {
- const session = await auth();
- if (!session?.user?.id) return 0;
- return prisma.notification.count({
- where: {
- isRead: false,
- toUserId: session?.user.id || '',
- },
- });
-}
diff --git a/apps/web/src/components/Navigation/notification-link.tsx b/apps/web/src/components/Navigation/notification-link.tsx
index 64e10ce7..0b1d86b3 100644
--- a/apps/web/src/components/Navigation/notification-link.tsx
+++ b/apps/web/src/components/Navigation/notification-link.tsx
@@ -5,18 +5,19 @@ import { track } from '@vercel/analytics';
import { useQuery } from '@tanstack/react-query';
import clsx from 'clsx';
import Link from 'next/link';
-import { getNotificationCount } from './navigation.actions';
+import { useTRPC } from '~/trpc/react';
-export const NOTIFICATION_QUERY_KEY = 'notificationCounts';
export function NotificationLink({ notificationCount }: { notificationCount: number }) {
+ const trpc = useTRPC();
// eventually lift this higher and pull new data and insert new rows into the notifications
// view if user is currently looking at it (example: twitter notif view)
- const { data: count } = useQuery({
- initialData: notificationCount,
- queryKey: [NOTIFICATION_QUERY_KEY],
- queryFn: () => getNotificationCount(),
- refetchInterval: 60000, // one minute
- });
+ const { data } = useQuery(
+ trpc.notification.getUnreadCount.queryOptions(undefined, {
+ initialData: notificationCount,
+ refetchInterval: 60000, // one minute
+ }),
+ );
+ const count = data ?? notificationCount;
return (
<Link
diff --git a/apps/web/src/server/api/root.ts b/apps/web/src/server/api/root.ts
new file mode 100644
index 00000000..ca8640e4
--- /dev/null
+++ b/apps/web/src/server/api/root.ts
@@ -0,0 +1,22 @@
+import { createCallerFactory, createTRPCRouter } from '~/server/api/trpc';
+import { notificationRouter } from './routers/notification';
+
+/**
+ * This is the primary router for your server.
+ *
+ * All routers added in /api/routers should be manually added here.
+ */
+export const appRouter = createTRPCRouter({
+ notification: notificationRouter,
+});
+
+// export type definition of API
+export type AppRouter = typeof appRouter;
+
+/**
+ * Create a server-side caller for the tRPC API.
+ * @example
+ * const trpc = createCaller(createContext);
+ * const res = await trpc.notification.getUnreadCount();
+ */
+export const createCaller = createCallerFactory(appRouter);
diff --git a/apps/web/src/server/api/routers/notification.ts b/apps/web/src/server/api/routers/notification.ts
new file mode 100644
index 00000000..ed216d7a
--- /dev/null
+++ b/apps/web/src/server/api/routers/notification.ts
@@ -0,0 +1,148 @@
+import { TRPCError } from '@trpc/server';
+import { z } from 'zod';
+
+import { createTRPCRouter, protectedProcedure } from '~/server/api/trpc';
+import { rateLimit } from '~/utils/rateLimit';
+
+const NOTIFICATIONS_PER_PAGE = 50;
+
+export const notificationRouter = createTRPCRouter({
+ /**
+ * Cursor-paginated notifications for the current user. Pass `mentionsOnly` to
+ * only return mention notifications.
+ */
+ getNotifications: protectedProcedure
+ .input(
+ z.object({
+ cursor: z.number().optional(),
+ mentionsOnly: z.boolean().optional().default(false),
+ }),
+ )
+ .query(async ({ ctx, input }) => {
+ const { cursor, mentionsOnly } = input;
+
+ const notifications = await ctx.db.notification.findMany({
+ take: NOTIFICATIONS_PER_PAGE,
+ skip: cursor ? 1 : 0,
+ cursor: cursor ? { id: cursor } : undefined,
+ where: {
+ toUserId: ctx.session.user.id,
+ type: mentionsOnly ? 'MENTION' : undefined,
+ },
+ select: {
+ id: true,
+ blurb: true,
+ createdAt: true,
+ url: true,
+ comment: {
+ select: {
+ id: true,
+ rootType: true,
+ text: true,
+ },
+ },
+ isRead: true,
+ content: true,
+ fromUser: {
+ select: {
+ image: true,
+ name: true,
+ },
+ },
+ type: true,
+ },
+ orderBy: [
+ {
+ createdAt: 'desc',
+ },
+ {
+ id: 'desc',
+ },
+ ],
+ });
+
+ if (notifications.length === 0) {
+ return {
+ notifications: [],
+ cursor: undefined,
+ };
+ }
+
+ const nextPage = await ctx.db.notification.findMany({
+ take: 1,
+ skip: 1,
+ cursor: { id: notifications.at(-1)?.id },
+ where: {
+ toUserId: ctx.session.user.id,
+ type: mentionsOnly ? 'MENTION' : undefined,
+ },
+ select: {
+ id: true,
+ },
+ orderBy: [
+ {
+ createdAt: 'desc',
+ },
+ {
+ id: 'desc',
+ },
+ ],
+ });
+
+ return {
+ notifications,
+ cursor: nextPage.length > 0 ? notifications.at(-1)?.id : undefined,
+ };
+ }),
+
+ /**
+ * Count of unread notifications for the current user.
+ */
+ getUnreadCount: protectedProcedure.query(async ({ ctx }) => {
+ return ctx.db.notification.count({
+ where: {
+ isRead: false,
+ toUserId: ctx.session.user.id,
+ },
+ });
+ }),
+
+ /**
+ * Marks the given notifications as read for the current user.
+ */
+ markAsRead: protectedProcedure
+ .input(z.object({ ids: z.array(z.number()) }))
+ .mutation(async ({ ctx, input }) => {
+ await ctx.db.notification.updateMany({
+ where: {
+ toUserId: ctx.session.user.id,
+ id: {
+ in: input.ids,
+ },
+ },
+ data: {
+ isRead: true,
+ },
+ });
+ }),
+
+ /**
+ * Marks all of the current user's notifications as read. Rate limited by IP.
+ */
+ markAllAsRead: protectedProcedure.mutation(async ({ ctx }) => {
+ const ip = ctx.headers.get('x-forwarded-for') ?? 'unknown';
+ const isRateLimited = rateLimit(ip);
+ if (isRateLimited) {
+ throw new TRPCError({ code: 'TOO_MANY_REQUESTS', message: 'Rate limit exceeded' });
+ }
+
+ await ctx.db.notification.updateMany({
+ where: {
+ toUserId: ctx.session.user.id,
+ },
+ data: {
+ isRead: true,
+ },
+ });
+ }),
+});
diff --git a/apps/web/src/server/api/trpc.ts b/apps/web/src/server/api/trpc.ts
new file mode 100644
index 00000000..e112b302
--- /dev/null
+++ b/apps/web/src/server/api/trpc.ts
@@ -0,0 +1,133 @@
+/**
+ * YOU PROBABLY DON'T NEED TO EDIT THIS FILE, UNLESS:
+ * 1. You want to modify request context (see Part 1).
+ * 2. You want to create a new middleware or type of procedure (see Part 3).
+ *
+ * TL;DR - This is where all the tRPC server stuff is created and plugged in. The pieces you will
+ * need to use are documented accordingly near the end.
+ */
+
+import { initTRPC, TRPCError } from '@trpc/server';
+import superjson from 'superjson';
+import { ZodError } from 'zod';
+
+import { auth } from '~/server/auth';
+import { prisma } from '@repo/db';
+
+/**
+ * 1. CONTEXT
+ *
+ * This section defines the "contexts" that are available in the backend API.
+ *
+ * These allow you to access things when processing a request, like the database, the session, etc.
+ *
+ * This helper generates the "internals" for a tRPC context. The API handler and RSC clients each
+ * wrap this and provides the required context.
+ *
+ * @see https://trpc.io/docs/server/context
+ */
+export const createTRPCContext = async (opts: { headers: Headers }) => {
+ const session = await auth();
+ return {
+ db: prisma,
+ session,
+ ...opts,
+ };
+};
+
+/**
+ * 2. INITIALIZATION
+ *
+ * This is where the tRPC API is initialized, connecting the context and transformer. We also parse
+ * ZodErrors so that you get typesafety on the frontend if your procedure fails due to validation
+ * errors on the backend.
+ */
+const t = initTRPC.context<Awaited<ReturnType<typeof createTRPCContext>>>().create({
+ transformer: superjson,
+ errorFormatter({ shape, error }) {
+ return {
+ ...shape,
+ data: {
+ ...shape.data,
+ zodError: error.cause instanceof ZodError ? error.cause.flatten() : null,
+ },
+ };
+ },
+});
+
+/**
+ * Create a server-side caller.
+ *
+ * @see https://trpc.io/docs/server/server-side-calls
+ */
+export const createCallerFactory = t.createCallerFactory;
+
+/**
+ * 3. ROUTER & PROCEDURE (THE IMPORTANT BIT)
+ *
+ * These are the pieces you use to build your tRPC API. You should import these a lot in the
+ * "/src/server/api/routers" directory.
+ */
+
+/**
+ * This is how you create new routers and sub-routers in your tRPC API.
+ *
+ * @see https://trpc.io/docs/router
+ */
+export const createTRPCRouter = t.router;
+
+/**
+ * Middleware for timing procedure execution and adding an artificial delay in development.
+ *
+ * You can remove this if you don't like it, but it can help catch unwanted waterfalls by simulating
+ * network latency that would occur in production but not in local development.
+ */
+const timingMiddleware = t.middleware(async ({ next, path }) => {
+ const start = Date.now();
+
+ if (t._config.isDev) {
+ // artificial delay in dev
+ const waitMs = Math.floor(Math.random() * 400) + 100;
+ await new Promise((resolve) => {
+ setTimeout(resolve, waitMs);
+ });
+ }
+
+ const result = await next();
+
+ const end = Date.now();
+ console.log(`[TRPC] ${path} took ${end - start}ms to execute`);
+
+ return result;
+});
+
+/**
+ * Public (unauthenticated) procedure
+ *
+ * This is the base piece you use to build new queries and mutations on your tRPC API. It does not
+ * guarantee that a user querying is authorized, but you can still access user session data if they
+ * are logged in.
+ *
+ * @see https://trpc.io/docs/procedures
+ */
+export const publicProcedure = t.procedure.use(timingMiddleware);
+
+/**
+ * Protected (authenticated) procedure
+ *
+ * If you want a query or mutation to ONLY be accessible to logged in users, use this. It verifies
+ * the session is valid and guarantees `ctx.session.user` is not null.
+ *
+ * @see https://trpc.io/docs/procedures
+ */
+export const protectedProcedure = t.procedure.use(timingMiddleware).use(({ ctx, next }) => {
+ if (!ctx.session?.user) {
+ throw new TRPCError({ code: 'UNAUTHORIZED' });
+ }
+ return next({
+ ctx: {
+ // infers the `session` as non-nullable
+ session: { ...ctx.session, user: ctx.session.user },
+ },
+ });
+});
diff --git a/apps/web/src/trpc/query-client.ts b/apps/web/src/trpc/query-client.ts
new file mode 100644
index 00000000..f1893f33
--- /dev/null
+++ b/apps/web/src/trpc/query-client.ts
@@ -0,0 +1,21 @@
+import { defaultShouldDehydrateQuery, QueryClient } from '@tanstack/react-query';
+import { deserialize, serialize } from 'superjson';
+
+export const createQueryClient = () =>
+ new QueryClient({
+ defaultOptions: {
+ queries: {
+ // With SSR, we usually want to set some default staleTime
+ // above 0 to avoid refetching immediately on the client
+ staleTime: 5000,
+ },
+ dehydrate: {
+ serializeData: serialize,
+ shouldDehydrateQuery: (query) =>
+ defaultShouldDehydrateQuery(query) || query.state.status === 'pending',
+ },
+ hydrate: {
+ deserializeData: deserialize,
+ },
+ },
+ });
diff --git a/apps/web/src/trpc/react.tsx b/apps/web/src/trpc/react.tsx
new file mode 100644
index 00000000..f554fd2d
--- /dev/null
+++ b/apps/web/src/trpc/react.tsx
@@ -0,0 +1,69 @@
+'use client';
+
+import type { QueryClient } from '@tanstack/react-query';
+import { QueryClientProvider } from '@tanstack/react-query';
+import { ReactQueryDevtools } from '@tanstack/react-query-devtools';
+import { createTRPCClient, httpBatchStreamLink, loggerLink } from '@trpc/client';
+import { createTRPCContext } from '@trpc/tanstack-react-query';
+import { useState } from 'react';
+import SuperJSON from 'superjson';
+
+import type { AppRouter } from './types';
+import { createQueryClient } from './query-client';
+
+export const { TRPCProvider, useTRPC, useTRPCClient } = createTRPCContext<AppRouter>();
+
+let clientQueryClientSingleton: QueryClient | undefined;
+const getQueryClient = () => {
+ if (typeof window === 'undefined') {
+ // Server: always make a new query client
+ return createQueryClient();
+ }
+ // Browser: use singleton pattern to keep the same query client
+ return (clientQueryClientSingleton ??= createQueryClient());
+};
+
+export function TRPCReactProvider(props: Readonly<{ children: React.ReactNode }>) {
+ // NOTE: Avoid useState when initializing the query client if you don't
+ // have a suspense boundary between this and the code that may
+ // suspend because React will throw away the client on the initial
+ // render if it suspends and there is no boundary
+ const queryClient = getQueryClient();
+
+ const [trpcClient] = useState(() =>
+ createTRPCClient<AppRouter>({
+ links: [
+ loggerLink({
+ enabled: (op) =>
+ process.env.NODE_ENV === 'development' ||
+ (op.direction === 'down' && op.result instanceof Error),
+ }),
+ httpBatchStreamLink({
+ transformer: SuperJSON,
+ url: `${getBaseUrl()}/api/trpc`,
+ headers() {
+ const headers = new Headers();
+ headers.set('x-trpc-source', 'nextjs-react');
+ return headers;
+ },
+ }),
+ ],
+ }),
+ );
+
+ return (
+ <QueryClientProvider client={queryClient}>
+ <ReactQueryDevtools initialIsOpen={false} buttonPosition="bottom-right" />
+ <TRPCProvider trpcClient={trpcClient} queryClient={queryClient}>
+ {props.children}
+ </TRPCProvider>
+ </QueryClientProvider>
+ );
+}
+
+function getBaseUrl() {
+ if (typeof window !== 'undefined') return window.location.origin;
+ if (process.env.VERCEL_URL) return `https://${process.env.VERCEL_URL}`;
+ // Match the web app's default next dev port
+ return `http://localhost:${process.env.PORT ?? 3000}`;
+}
diff --git a/apps/web/src/trpc/server.tsx b/apps/web/src/trpc/server.tsx
new file mode 100644
index 00000000..b1622fdf
--- /dev/null
+++ b/apps/web/src/trpc/server.tsx
@@ -0,0 +1,66 @@
+import 'server-only';
+
+import { dehydrate, HydrationBoundary } from '@tanstack/react-query';
+import { createTRPCOptionsProxy, type TRPCQueryOptions } from '@trpc/tanstack-react-query';
+import { headers } from 'next/headers';
+import { cache } from 'react';
+
+import { appRouter, createCaller } from '~/server/api/root';
+import { createTRPCContext } from '~/server/api/trpc';
+import { createQueryClient } from './query-client';
+
+/**
+ * This wraps the `createTRPCContext` helper and provides the required context for the tRPC API when
+ * handling a tRPC call from a React Server Component.
+ */
+const createContext = cache(async () => {
+ const heads = new Headers(await headers());
+ heads.set('x-trpc-source', 'rsc');
+
+ return createTRPCContext({
+ headers: heads,
+ });
+});
+
+/**
+ * IMPORTANT: Create a stable getter for the query client that will return the same client during
+ * the same request.
+ */
+export const getQueryClient = cache(createQueryClient);
+
+/**
+ * Direct server caller for reading data in Server Components.
+ *
+ * This is detached from the React Query cache — use `trpc` + `prefetch` when you need to hydrate
+ * data into Client Components.
+ *
+ * @see https://trpc.io/docs/client/nextjs/server-components#getting-data-in-a-server-component
+ */
+export const api = createCaller(createContext);
+
+/**
+ * Options proxy for prefetching queries into the per-request QueryClient.
+ *
+ * @see https://trpc.io/docs/client/tanstack-react-query/server-components
+ */
+export const trpc = createTRPCOptionsProxy({
+ ctx: createContext,
+ router: appRouter,
+ queryClient: getQueryClient,
+});
+
+export function HydrateClient(props: { children: React.ReactNode }) {
+ const queryClient = getQueryClient();
+ return <HydrationBoundary state={dehydrate(queryClient)}>{props.children}</HydrationBoundary>;
+}
+
+// eslint-disable-next-line @typescript-eslint/no-explicit-any
+export function prefetch(queryOptions: ReturnType<TRPCQueryOptions<any>>) {
+ const queryClient = getQueryClient();
+ if (queryOptions.queryKey[1]?.type === 'infinite') {
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ void queryClient.prefetchInfiniteQuery(queryOptions as any);
+ } else {
+ void queryClient.prefetchQuery(queryOptions);
+ }
+}
diff --git a/apps/web/src/trpc/types.ts b/apps/web/src/trpc/types.ts
new file mode 100644
index 00000000..7f779577
--- /dev/null
+++ b/apps/web/src/trpc/types.ts
@@ -0,0 +1,19 @@
+import type { inferRouterInputs, inferRouterOutputs } from '@trpc/server';
+
+import type { AppRouter } from '~/server/api/root';
+
+export type { AppRouter };
+
+/**
+ * Inference helper for inputs.
+ *
+ * @example type NotificationsInput = RouterInputs['notification']['getNotifications']
+ */
+export type RouterInputs = inferRouterInputs<AppRouter>;
+
+/**
+ * Inference helper for outputs.
+ *
+ * @example type NotificationsOutput = RouterOutputs['notification']['getNotifications']
+ */
+export type RouterOutputs = inferRouterOutputs<AppRouter>;
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 61bf03ab..fba3a973 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -493,6 +493,15 @@ importers:
'@tanstack/react-table':
specifier: ^8.20.5
+ '@trpc/client':
+ specifier: 11.18.0
+ '@trpc/server':
+ specifier: 11.18.0
+ version: 11.18.0([email protected])
+ '@trpc/tanstack-react-query':
+ specifier: 11.18.0
'@uiw/react-md-editor':
specifier: ^4.0.4