Open-source status page, incident response and uptime monitoring
TypeScript alertingincident-managementmcpmcp-servermonitoringmonitoring-as-codeobservabilityon-callopen-sourcesrestatus-pagestatuspagesynthetic-monitoringterraformtinybirdtursouptimeuptime-checkeruptime-monitor
import {
type EventProps,
Events,
type IdentifyProps,
parseInputToProps,
setupAnalytics,
} from "@openstatus/analytics";
import { db } from "@openstatus/db";
import type { User, Workspace } from "@openstatus/db/src/schema";
import { LimitExceededError } from "@openstatus/services";
import { TRPCError, initTRPC } from "@trpc/server";
import { type NextRequest, after } from "next/server.js";
import superjson from "superjson";
import { ZodError, treeifyError } from "zod";
import {
type ResolveActiveWorkspaceResult,
resolveActiveWorkspace,
resolveUserWorkspaces,
} from "./auth/resolve-active-workspace";
// Generic session type that works with both User and Viewer
type Session = {
user?: {
id?: string | null;
email?: string | null;
} | null;
} | null;
/**
* 1. CONTEXT
*
* This section defines the "contexts" that are available in the backend API
*
* These allow you to access things like the database, the session, etc, when
* processing a request
*
*/
type CreateContextOptions = {
session: Session | null;
workspace?: Workspace | null;
workspaces?: Workspace[] | null;
user?: User | null;
req?: NextRequest;
metadata?: {
userAgent?: string;
location?: string;
};
resolveWorkspace?: () => Promise<ResolveActiveWorkspaceResult>;
};
type Meta = {
track?: EventProps;
trackProps?: string[];
/**
* Props derived from the raw input and the procedure's result, merged over
* `trackProps`. Return `null` to skip the event for this call.
*/
trackResult?: (args: {
input: unknown;
data: unknown;
}) => Record<string, unknown> | null;
};
/**
* This helper generates the "internals" for a tRPC context. If you need to use
* it, you can export it from here
*
* Examples of things you may need it for:
* - testing, so we dont have to mock Next.js' req/res
* - trpc's `createSSGHelpers` where we don't have req/res
* @see https://create.t3.gg/en/usage/trpc#-servertrpccontextts
*/
export const createInnerTRPCContext = (opts: CreateContextOptions) => {
return {
...opts,
db,
};
};
/**
* This is the actual context you'll use in your router. It will be used to
* process every request that goes through your tRPC endpoint
* @link https://trpc.io/docs/context
*/
export const createTRPCContext = async (opts: {
req: NextRequest;
serverSideCall?: boolean;
auth?: () => Promise<Session>;
}) => {
// Use provided auth function or return null session
const session = opts.auth ? await opts.auth() : null;
const workspace = null;
const workspaces = null;
const user = null;
// Context is per HTTP request while middleware runs per procedure — a
// batched request would otherwise re-run the same user×workspaces query
// once per procedure. Zero-arg by design: userId/slug are bound here so
// the first call's promise is safe to share across the whole batch.
let resolution: Promise<ResolveActiveWorkspaceResult> | undefined;
const resolveWorkspace = () =>
(resolution ??= resolveActiveWorkspace({
userId: Number(session?.user?.id),
workspaceSlug: opts.req.cookies.get("workspace-slug")?.value,
}));
return createInnerTRPCContext({
session,
workspace,
workspaces,
user,
resolveWorkspace,
req: opts.req,
metadata: {
userAgent: opts.req.headers.get("user-agent") ?? undefined,
location:
opts.req.headers.get("x-forwarded-for") ??
process.env.VERCEL_REGION ??
undefined,
},
});
};
export type Context = Awaited<ReturnType<typeof createTRPCContext>>;
/**
* 2. INITIALIZATION
*
* This is where the trpc api is initialized, connecting the context and
* transformer
*/
export const t = initTRPC
.context<Context>()
.meta<Meta>()
.create({
transformer: superjson,
errorFormatter({ shape, error }) {
return {
...shape,
data: {
...shape.data,
zodError:
error.cause instanceof ZodError ? treeifyError(error.cause) : null,
},
};
},
});
/**
* 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 folder
*/
/**
* This is how you create new routers and subrouters in your tRPC API
* @see https://trpc.io/docs/router
*/
export const createTRPCRouter = t.router;
export const mergeRouters = t.mergeRouters;
const timingMiddleware = t.middleware(async (opts) => {
const start = performance.now();
const result = await opts.next();
if (process.env.NODE_ENV !== "test") {
const durationMs = Math.round(performance.now() - start);
console.info(
JSON.stringify({
msg: "trpc.timing",
path: opts.path,
type: opts.type,
durationMs,
ok: result.ok,
region: process.env.VERCEL_REGION,
}),
);
}
return result;
});
/**
* Public (unauthed) 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
*/
export const publicProcedure = t.procedure.use(timingMiddleware);
/**
* Reusable middleware that enforces users are logged in before running the
* procedure
*/
const enforceUserIsAuthed = t.middleware(async (opts) => {
const { ctx } = opts;
if (!ctx.session?.user?.id) {
throw new TRPCError({ code: "UNAUTHORIZED" });
}
// Test escape hatch: when NODE_ENV=test and the caller already
// populated `workspace` + `user` on the inner context (via
// `createInnerTRPCContext` in a test helper), trust it and skip the
// DB round-trip. Without this, router-level limit tests that pass
// an override `workspace.limits` object see it immediately replaced
// by the seeded team-plan workspace below — the override never
// reaches the service and the test asserts against the wrong plan.
if (
process.env.NODE_ENV === "test" &&
ctx.workspace != null &&
ctx.user != null
) {
return opts.next({
ctx: {
...ctx,
user: ctx.user,
workspace: ctx.workspace,
workspaces: ctx.workspaces ?? [ctx.workspace],
},
});
}
/**
* The active "workspace-slug" cookie is set in the dashboard middleware
* for server requests and in `<WorkspaceClientCookie />` for client
* requests; we read the same cookie either way.
*/
const workspaceSlug = ctx.req?.cookies.get("workspace-slug")?.value;
const resolved = await (ctx.resolveWorkspace
? ctx.resolveWorkspace()
: resolveActiveWorkspace({
userId: Number(ctx.session.user.id),
workspaceSlug,
}));
if (!resolved.ok) {
throw new TRPCError({
code: "UNAUTHORIZED",
message:
resolved.error.kind === "user_not_found"
? "User Not Found"
: "Workspace Not Found",
});
}
const { user, workspace, workspaces } = resolved.value;
if (workspace.slug !== workspaceSlug) {
// properly set the workspace slug cookie
ctx.req?.cookies.set("workspace-slug", workspace.slug);
}
const result = await opts.next({
ctx: { ...ctx, user, workspace, workspaces },
});
if (process.env.NODE_ENV === "test") {
return result;
}
const identify: IdentifyProps = {
userAgent: ctx.metadata?.userAgent,
location: ctx.metadata?.location,
source: "dashboard",
userId: `usr_${user.id}`,
email: user.email || undefined,
workspaceId: String(workspace.id),
workspaceName: workspace.name || workspace.slug,
plan: workspace.plan,
};
if (!result.ok) {
const cause = result.error.cause;
if (cause instanceof LimitExceededError) {
after(async () => {
const analytics = await setupAnalytics(identify);
await analytics.track({
...Events.ReachLimit,
limit: cause.limit,
max: cause.max,
current: cause.current,
procedure: opts.path,
});
});
}
return result;
}
// REMINDER: We only track the event if the request was successful
// REMINDER: We are not blocking the request
after(async () => {
const { meta, getRawInput } = opts;
if (meta?.track) {
const rawInput = await getRawInput();
const resultProps = meta.trackResult
? meta.trackResult({ input: rawInput, data: result.data })
: {};
if (resultProps === null) return;
const analytics = await setupAnalytics(identify);
const additionalProps = parseInputToProps(rawInput, meta.trackProps);
await analytics.track({
...additionalProps,
...resultProps,
...meta.track,
});
}
});
return result;
});
/**
* Middleware to parse form data and put it in the rawInput
*/
export const formdataMiddleware = t.middleware(async (opts) => {
const formData = await opts.ctx.req?.formData?.();
if (!formData) throw new TRPCError({ code: "BAD_REQUEST" });
return opts.next({
input: formData,
});
});
/**
* Signed-in user without an active workspace. `ctx.workspaces` may be empty;
* `ctx.workspace` stays null. Only for surfaces that must render for a user
* who belongs to no workspace — everything else uses `protectedProcedure`.
*/
const enforceUserIsSignedIn = t.middleware(async (opts) => {
const { ctx } = opts;
if (!ctx.session?.user?.id) {
throw new TRPCError({ code: "UNAUTHORIZED" });
}
const resolved = await resolveUserWorkspaces({
userId: Number(ctx.session.user.id),
});
if (!resolved) {
throw new TRPCError({ code: "UNAUTHORIZED", message: "User Not Found" });
}
return opts.next({
ctx: { ...ctx, user: resolved.user, workspaces: resolved.workspaces },
});
});
export const userProcedure = t.procedure
.use(timingMiddleware)
.use(enforceUserIsSignedIn);
/**
* Protected (authed) 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(enforceUserIsAuthed);