Skip to content

Open-source status page, incident response and uptime monitoring

trpc: use proxy for rsc (#2546)

Thibault Le Ouaya5bc7c8feab5
diff --git a/apps/dashboard/src/lib/trpc/server.tsx b/apps/dashboard/src/lib/trpc/server.tsx
index bbdb021c8..b419988f0 100644
--- a/apps/dashboard/src/lib/trpc/server.tsx
+++ b/apps/dashboard/src/lib/trpc/server.tsx
@@ -1,111 +1,15 @@
import "server-only";
-import { appRouter, createTRPCContext } from "@openstatus/api";
-import { HydrationBoundary } from "@tanstack/react-query";
-import { dehydrate } from "@tanstack/react-query";
-import { TRPCClientError } from "@trpc/client";
-import { TRPCError } from "@trpc/server";
-import {
- type ResolverDef,
- type TRPCQueryOptions,
- createTRPCOptionsProxy,
-} from "@trpc/tanstack-react-query";
-import { headers } from "next/headers";
-import { notFound } from "next/navigation";
-import { NextRequest } from "next/server";
-import { cache } from "react";
+import { createServerHelpers } from "@openstatus/api/src/rsc";
import { auth } from "@/lib/auth";
import { makeQueryClient } from "./query-client";
-// IMPORTANT: Create a stable getter for the query client that
-// will return the same client during the same request.
-export const getQueryClient = cache(makeQueryClient);
-
-// `cache` is load-bearing: the options proxy unwraps this factory on every
-// procedure call, so without it each prefetch would re-run `auth()`.
-const getContext = cache(async () => {
- const incoming = await headers();
- return createTRPCContext({
- // NextRequest derives `cookies` from the cookie header, and `ctx.req` is
- // only ever read for cookies and headers.
- req: new NextRequest("http://rsc.internal", {
- headers: new Headers(incoming),
- }),
- auth,
- });
-});
-
-export const trpc = createTRPCOptionsProxy({
- router: appRouter,
- ctx: getContext,
- queryClient: getQueryClient,
-});
-
-export function HydrateClient(props: { children: React.ReactNode }) {
- const queryClient = getQueryClient();
-
- return (
- <HydrationBoundary state={dehydrate(queryClient)}>
- {props.children}
- </HydrationBoundary>
- );
-}
-
-// oxlint-disable-next-line typescript/no-explicit-any -- FIXME: remove any
-export function prefetch<T extends ReturnType<TRPCQueryOptions<any>>>(
- queryOptions: T,
-) {
- const queryClient = getQueryClient();
-
- if (queryOptions.queryKey[1]?.type === "infinite") {
- // oxlint-disable-next-line typescript/no-explicit-any -- FIXME: remove any
- void queryClient.prefetchInfiniteQuery(queryOptions as any);
- } else {
- void queryClient.prefetchQuery(queryOptions);
- }
-}
-
-// oxlint-disable-next-line typescript/no-explicit-any -- FIXME: remove any
-export function batchPrefetch<T extends ReturnType<TRPCQueryOptions<any>>>(
- queryOptionsArray: T[],
-) {
- const queryClient = getQueryClient();
-
- for (const queryOptions of queryOptionsArray) {
- if (queryOptions.queryKey[1]?.type === "infinite") {
- // oxlint-disable-next-line typescript/no-explicit-any -- FIXME: remove any
- void queryClient.prefetchInfiniteQuery(queryOptions as any);
- } else {
- void queryClient.prefetchQuery(queryOptions);
- }
- }
-}
-
-/**
- * Fetches a query and calls `notFound()` if the server returns NOT_FOUND.
- * Use this for gating queries in layouts where the resource must exist.
- */
-export async function fetchQueryOrNotFound<
- T extends ReturnType<TRPCQueryOptions<ResolverDef>>,
->(queryOptions: T) {
- const queryClient = getQueryClient();
- try {
- return (await queryClient.fetchQuery(queryOptions)) as Awaited<
- ReturnType<Extract<T["queryFn"], (...args: never[]) => unknown>>
- >;
- } catch (error) {
- // Direct router calls throw `TRPCError`; the browser client throws
- // `TRPCClientError`. Both reach here depending on the caller.
- const code =
- error instanceof TRPCError
- ? error.code
- : error instanceof TRPCClientError
- ? error.data?.code
- : undefined;
- if (code === "NOT_FOUND") {
- notFound();
- }
- throw error;
- }
-}
+export const {
+ trpc,
+ getQueryClient,
+ HydrateClient,
+ prefetch,
+ batchPrefetch,
+ fetchQueryOrNotFound,
+} = createServerHelpers({ makeQueryClient, auth });
diff --git a/apps/status-page/src/lib/trpc/query-client.ts b/apps/status-page/src/lib/trpc/query-client.ts
index 4fd826fe5..2eb918378 100644
--- a/apps/status-page/src/lib/trpc/query-client.ts
+++ b/apps/status-page/src/lib/trpc/query-client.ts
@@ -1,10 +1,20 @@
+import * as Sentry from "@sentry/nextjs";
import {
+ QueryCache,
QueryClient,
defaultShouldDehydrateQuery,
} from "@tanstack/react-query";
export function makeQueryClient() {
return new QueryClient({
+ // `prefetchQuery` swallows rejections, so the cache is the only place left
+ // to observe a failed server-side prefetch.
+ queryCache: new QueryCache({
+ onError: (error, query) =>
+ Sentry.captureException(error, {
+ extra: { queryHash: query.queryHash },
+ }),
+ }),
defaultOptions: {
queries: {
staleTime: 60 * 1000,
diff --git a/apps/status-page/src/lib/trpc/server.tsx b/apps/status-page/src/lib/trpc/server.tsx
index 726febc80..7bfde338b 100644
--- a/apps/status-page/src/lib/trpc/server.tsx
+++ b/apps/status-page/src/lib/trpc/server.tsx
@@ -1,83 +1,19 @@
import "server-only";
-import type { AppRouter } from "@openstatus/api";
-import { HydrationBoundary } from "@tanstack/react-query";
-import { dehydrate } from "@tanstack/react-query";
-import { createTRPCClient } from "@trpc/client";
-import {
- type TRPCQueryOptions,
- createTRPCOptionsProxy,
-} from "@trpc/tanstack-react-query";
-import { cookies } from "next/headers";
-import { cache } from "react";
+import { createServerHelpers } from "@openstatus/api/src/rsc";
+import { auth } from "../auth";
import { makeQueryClient } from "./query-client";
-import { endingLink, sentryLoggerLink } from "./shared";
-// IMPORTANT: Create a stable getter for the query client that
-// will return the same client during the same request.
-export const getQueryClient = cache(makeQueryClient);
-
-export const trpc = createTRPCOptionsProxy<AppRouter>({
- queryClient: getQueryClient,
- client: createTRPCClient({
- links: [
- sentryLoggerLink(),
- endingLink({
- headers: {
- "x-trpc-source": "server",
- },
- fetch: async (url, options) => {
- const cookieStore = await cookies();
- return fetch(url, {
- ...options,
- credentials: "include",
- headers: {
- ...options?.headers,
- cookie: cookieStore.toString(),
- },
- });
- },
- }),
- ],
- }),
+export const {
+ trpc,
+ getQueryClient,
+ HydrateClient,
+ prefetch,
+ batchPrefetch,
+ fetchQueryOrNotFound,
+} = createServerHelpers({
+ // Lazy: `../auth` imports this module, so referencing `auth` eagerly would
+ // hit a circular-init TDZ.
+ makeQueryClient,
+ auth: () => auth(),
});
-
-export function HydrateClient(props: { children: React.ReactNode }) {
- const queryClient = getQueryClient();
-
- return (
- <HydrationBoundary state={dehydrate(queryClient)}>
- {props.children}
- </HydrationBoundary>
- );
-}
-
-// oxlint-disable-next-line typescript/no-explicit-any -- FIXME: remove any
-export function prefetch<T extends ReturnType<TRPCQueryOptions<any>>>(
- queryOptions: T,
-) {
- const queryClient = getQueryClient();
-
- if (queryOptions.queryKey[1]?.type === "infinite") {
- // oxlint-disable-next-line typescript/no-explicit-any -- FIXME: remove any
- void queryClient.prefetchInfiniteQuery(queryOptions as any);
- } else {
- void queryClient.prefetchQuery(queryOptions);
- }
-}
-
-// oxlint-disable-next-line typescript/no-explicit-any -- FIXME: remove any
-export function batchPrefetch<T extends ReturnType<TRPCQueryOptions<any>>>(
- queryOptionsArray: T[],
-) {
- const queryClient = getQueryClient();
-
- for (const queryOptions of queryOptionsArray) {
- if (queryOptions.queryKey[1]?.type === "infinite") {
- // oxlint-disable-next-line typescript/no-explicit-any -- FIXME: remove any
- void queryClient.prefetchInfiniteQuery(queryOptions as any);
- } else {
- void queryClient.prefetchQuery(queryOptions);
- }
- }
-}
diff --git a/packages/api/package.json b/packages/api/package.json
index b6cfb9e22..832c5fd63 100644
--- a/packages/api/package.json
+++ b/packages/api/package.json
@@ -16,6 +16,7 @@
"env": "deno run -A env.ts"
},
"dependencies": {
+ "@libsql/client": "catalog:",
"@openstatus/analytics": "workspace:*",
"@openstatus/assertions": "workspace:*",
"@openstatus/db": "workspace:*",
@@ -37,20 +38,25 @@
"@openstatus/regions": "workspace:*",
"@openstatus/services": "workspace:*",
"@openstatus/subscriptions": "workspace:*",
+ "@openstatus/theme-store": "workspace:*",
"@openstatus/tinybird": "workspace:*",
"@openstatus/upstash": "workspace:*",
"@openstatus/utils": "workspace:*",
"@t3-oss/env-core": "catalog:",
+ "@tanstack/react-query": "catalog:",
"@trpc/client": "catalog:",
"@trpc/server": "catalog:",
+ "@trpc/tanstack-react-query": "catalog:",
"@unkey/api": "catalog:",
"@vercel/blob": "catalog:",
"date-fns": "catalog:",
+ "drizzle-orm": "catalog:",
"isomorphic-dompurify": "catalog:",
"nanoid": "catalog:",
"nanoid-dictionary": "catalog:",
"next": "catalog:",
"random-word-slugs": "catalog:",
+ "react": "catalog:",
"stripe": "catalog:",
"superjson": "catalog:",
"zod": "catalog:"
diff --git a/packages/api/src/rsc.ts b/packages/api/src/rsc.ts
new file mode 100644
index 000000000..86efd7b46
--- /dev/null
+++ b/packages/api/src/rsc.ts
@@ -0,0 +1,134 @@
+import {
+ HydrationBoundary,
+ type QueryClient,
+ dehydrate,
+} from "@tanstack/react-query";
+import { TRPCClientError } from "@trpc/client";
+import { TRPCError } from "@trpc/server";
+import {
+ type ResolverDef,
+ type TRPCOptionsProxy,
+ type TRPCQueryOptions,
+ createTRPCOptionsProxy,
+} from "@trpc/tanstack-react-query";
+import { headers } from "next/headers";
+import { notFound } from "next/navigation";
+import { NextRequest } from "next/server";
+import { type ReactNode, cache, createElement } from "react";
+
+import { type AppRouter, appRouter } from "./root";
+import { createTRPCContext } from "./trpc";
+
+type AuthFn = NonNullable<Parameters<typeof createTRPCContext>[0]["auth"]>;
+
+/**
+ * Builds the per-app RSC tRPC helpers around a direct, in-process router proxy
+ * (no HTTP hop). `auth` is passed lazily so an app whose auth module imports
+ * these helpers doesn't hit a circular-init TDZ.
+ */
+export function createServerHelpers(opts: {
+ makeQueryClient: () => QueryClient;
+ auth?: AuthFn;
+}) {
+ // Stable per-request getter so the same client is reused across a request.
+ const getQueryClient = cache(opts.makeQueryClient);
+
+ // `cache` is load-bearing: the options proxy unwraps this factory on every
+ // procedure call, so without it each prefetch would re-run `auth()`.
+ const getContext = cache(async () => {
+ const incoming = await headers();
+ return createTRPCContext({
+ // NextRequest derives `cookies` from the cookie header, and `ctx.req` is
+ // only ever read for cookies and headers.
+ req: new NextRequest("http://rsc.internal", {
+ headers: new Headers(incoming),
+ }),
+ auth: opts.auth,
+ });
+ });
+
+ // Annotated (not inferred) so the exported type stays nameable across the
+ // package boundary — the inferred proxy type reaches into non-portable
+ // drizzle/libsql/theme-store paths (TS2742).
+ const trpc: TRPCOptionsProxy<AppRouter> = createTRPCOptionsProxy({
+ router: appRouter,
+ ctx: getContext,
+ queryClient: getQueryClient,
+ });
+
+ function HydrateClient(props: { children: ReactNode }) {
+ const queryClient = getQueryClient();
+ return createElement(
+ HydrationBoundary,
+ { state: dehydrate(queryClient) },
+ props.children,
+ );
+ }
+
+ // oxlint-disable-next-line typescript/no-explicit-any -- FIXME: remove any
+ function prefetch<T extends ReturnType<TRPCQueryOptions<any>>>(
+ queryOptions: T,
+ ) {
+ const queryClient = getQueryClient();
+
+ if (queryOptions.queryKey[1]?.type === "infinite") {
+ // oxlint-disable-next-line typescript/no-explicit-any -- FIXME: remove any
+ void queryClient.prefetchInfiniteQuery(queryOptions as any);
+ } else {
+ void queryClient.prefetchQuery(queryOptions);
+ }
+ }
+
+ // oxlint-disable-next-line typescript/no-explicit-any -- FIXME: remove any
+ function batchPrefetch<T extends ReturnType<TRPCQueryOptions<any>>>(
+ queryOptionsArray: T[],
+ ) {
+ const queryClient = getQueryClient();
+
+ for (const queryOptions of queryOptionsArray) {
+ if (queryOptions.queryKey[1]?.type === "infinite") {
+ // oxlint-disable-next-line typescript/no-explicit-any -- FIXME: remove any
+ void queryClient.prefetchInfiniteQuery(queryOptions as any);
+ } else {
+ void queryClient.prefetchQuery(queryOptions);
+ }
+ }
+ }
+
+ /**
+ * Fetches a query and calls `notFound()` if the server returns NOT_FOUND.
+ * Use this for gating queries in layouts where the resource must exist.
+ */
+ async function fetchQueryOrNotFound<
+ T extends ReturnType<TRPCQueryOptions<ResolverDef>>,
+ >(queryOptions: T) {
+ const queryClient = getQueryClient();
+ try {
+ return (await queryClient.fetchQuery(queryOptions)) as Awaited<
+ ReturnType<Extract<T["queryFn"], (...args: never[]) => unknown>>
+ >;
+ } catch (error) {
+ // Direct router calls throw `TRPCError`; the browser client throws
+ // `TRPCClientError`. Both reach here depending on the caller.
+ const code =
+ error instanceof TRPCError
+ ? error.code
+ : error instanceof TRPCClientError
+ ? error.data?.code
+ : undefined;
+ if (code === "NOT_FOUND") {
+ notFound();
+ }
+ throw error;
+ }
+ }
+
+ return {
+ trpc,
+ getQueryClient,
+ HydrateClient,
+ prefetch,
+ batchPrefetch,
+ fetchQueryOrNotFound,
+ };
+}
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 189e28762..bf8783b2e 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -1780,6 +1780,9 @@ importers:
packages/api:
dependencies:
+ '@libsql/client':
+ specifier: 'catalog:'
+ version: 0.17.4
'@openstatus/analytics':
specifier: workspace:*
version: link:../analytics
@@ -1843,6 +1846,9 @@ importers:
'@openstatus/subscriptions':
specifier: workspace:*
version: link:../subscriptions
+ '@openstatus/theme-store':
+ specifier: workspace:*
+ version: link:../theme-store
'@openstatus/tinybird':
specifier: workspace:*
version: link:../tinybird
@@ -1855,12 +1861,18 @@ importers:
'@t3-oss/env-core':
specifier: 'catalog:'
+ '@tanstack/react-query':
+ specifier: 'catalog:'
+ version: 5.100.11([email protected])
'@trpc/client':
specifier: 'catalog:'
'@trpc/server':
specifier: 'catalog:'
version: 11.17.0([email protected])
+ '@trpc/tanstack-react-query':
+ specifier: 'catalog:'
'@unkey/api':
specifier: 'catalog:'
version: 2.3.4
@@ -1870,6 +1882,9 @@ importers:
date-fns:
specifier: 'catalog:'
version: 3.6.0
+ drizzle-orm:
+ specifier: 'catalog:'
+ version: 0.45.2(@libsql/[email protected])(@opentelemetry/[email protected])(@types/[email protected])(@upstash/[email protected])([email protected])
isomorphic-dompurify:
specifier: 'catalog:'
version: 3.14.0(@noble/[email protected])
@@ -1885,6 +1900,9 @@ importers:
random-word-slugs:
specifier: 'catalog:'
version: 0.1.7
+ react:
+ specifier: 'catalog:'
+ version: 19.2.6
stripe:
specifier: 'catalog:'
version: 13.11.0