0Pricing
tRPC End-to-End Type Safe APIs · Lektion

Benutzerdefinierte Middleware-Ketten

Erstellen Sie benutzerdefinierte Middleware für Logging, Rate-Limiting oder Autorisierung und verketten Sie diese miteinander.

Benutzerdefinierte Middleware-Ketten ist eine kostenlose tRPC End-to-End Type Safe APIs-Lektion auf CoddyKit. Dies ist Lektion 3 von 4. Du kannst die komplette Lektion unten kostenlos lesen – dann übst du sie direkt im Browser mit einem integrierten Code-Editor und einem KI-Tutor rund um die Uhr. Sie ist Teil des tRPC End-to-End Type Safe APIs-Lernpfads, und dein Fortschritt wird über Web und CoddyKit-App synchronisiert. Der tRPC End-to-End Type Safe APIs-Kurs umfasst insgesamt 4 Lektionen.

Teile dieser Lektion wurden noch nicht übersetzt und werden auf Englisch angezeigt.

Chain Multiple Middleware

In tRPC, middleware lets you run logic before your procedure executes. What if you need multiple checks, like logging, authentication, and validation, for a single API call?

This is where middleware chains come in handy! They allow you to stack multiple middleware functions, executing them one after another.

Benefits of Chaining

Chaining middleware offers several advantages:

  • Modularity: Each middleware focuses on a single responsibility (e.g., logging, auth).
  • Reusability: Create generic middleware that can be applied to different procedures or routers.
  • Order of Execution: Control the exact sequence of operations before your main procedure logic runs.
  • Early Exit: A middleware can stop the chain early if a condition isn't met (e.g., unauthorized access).

How `next()` Works

Recall that tRPC middleware receives a next function. Calling next() passes control to the next middleware in the chain, or to the actual procedure handler if it's the last middleware.

If a middleware doesn't call next(), the chain stops, and the procedure handler will not execute. This is crucial for checks like authentication!

First: Logging Middleware

Let's create a simple logging middleware. It will log when a request starts and how long it took. This is a common pattern for monitoring.

Notice how next() is awaited to ensure the procedure (and subsequent middleware) completes before logging the duration.

type Context = { userId: string | null };
const trpc = {
  middleware: (handler: any) => handler,
  procedure: {
    use: (mw: any) => ({
      query: (f: any) => f,
      mutation: (f: any) => f
    }),
    query: (f: any) => f,
    mutation: (f: any) => f
  },
  router: (cfg: any) => cfg,
};

const logMiddleware = trpc.middleware(async ({ path, type, next }) => {
  console.log(`[${type}] Request to ${path} started.`);
  const start = Date.now();
  const result = await next();
  const durationMs = Date.now() - start;
  console.log(`[${type}] Request to ${path} finished in ${durationMs}ms.`);
  return result;
});

const appRouter = trpc.router({
  example: trpc.procedure
    .use(logMiddleware)
    .query(() => "Data fetched!")
});

Second: Auth Middleware

Next, we'll build an authentication middleware. This middleware will check if a user is logged in (i.e., if ctx.userId exists). If not, it will throw an error, effectively stopping the procedure.

Remember, the ctx (context) object is passed to middleware, allowing access to request-specific data.

type Context = { userId: string | null };
const trpc = {
  middleware: (handler: any) => handler,
  procedure: {
    use: (mw: any) => ({
      query: (f: any) => f,
      mutation: (f: any) => f
    }),
    query: (f: any) => f,
    mutation: (f: any) => f
  },
  router: (cfg: any) => cfg,
};

const isAuthenticated = trpc.middleware(async ({ ctx, next }) => {
  if (!ctx.userId) {
    throw new Error("UNAUTHORIZED: Please log in.");
  }
  return next();
});

const appRouter = trpc.router({
  protected: trpc.procedure
    .use(isAuthenticated)
    .query(({ ctx }) => `Welcome, user ${ctx.userId}!`)
});

Building a Middleware Chain

Now, let's combine our logMiddleware and isAuthenticated middleware. The order matters: logging should happen first, then authentication.

We simply use .use() multiple times. tRPC will execute them in the order they are defined.

type Context = { userId: string | null };
const trpc = {
  middleware: (handler: any) => handler,
  procedure: {
    use: (mw: any) => ({
      query: (f: any) => f,
      mutation: (f: any) => f
    }),
    query: (f: any) => f,
    mutation: (f: any) => f
  },
  router: (cfg: any) => cfg,
};

const logMiddleware = trpc.middleware(async ({ path, type, next }) => {
  console.log(`[${type}] Request to ${path} started.`);
  const start = Date.now();
  const result = await next();
  const durationMs = Date.now() - start;
  console.log(`[${type}] Request to ${path} finished in ${durationMs}ms.`);
  return result;
});

const isAuthenticated = trpc.middleware(async ({ ctx, next }) => {
  if (!ctx.userId) {
    throw new Error("UNAUTHORIZED: Please log in.");
  }
  return next();
});

const appRouter = trpc.router({
  protectedData: trpc.procedure
    .use(logMiddleware)
    .use(isAuthenticated)
    .query(({ ctx }) => `Secret data for ${ctx.userId}!`)
});

Order of Execution

When a request hits protectedData:

  1. logMiddleware runs first.
  2. If logMiddleware calls next(), then isAuthenticated runs.
  3. If isAuthenticated calls next(), then the actual query procedure handler runs.
  4. If any middleware throws an error (like isAuthenticated), the chain stops immediately, and the error is returned.

Dynamic Middleware

What if you need different authorization levels? You can create a function that returns a middleware, allowing for dynamic configuration.

This pattern is called a middleware builder and is powerful for creating flexible and reusable middleware.

type Context = { userId: string | null; userRole: string | null };
const trpc = {
  middleware: (handler: any) => handler,
  procedure: {
    use: (mw: any) => ({
      query: (f: any) => f,
      mutation: (f: any) => f
    }),
    query: (f: any) => f,
    mutation: (f: any) => f
  },
  router: (cfg: any) => cfg,
};

const hasRole = (requiredRole: string) => {
  return trpc.middleware(async ({ ctx, next }) => {
    if (!ctx.userRole || ctx.userRole !== requiredRole) {
      throw new Error(`FORBIDDEN: ${requiredRole} role required.`);
    }
    return next();
  });
};

const appRouter = trpc.router({
  adminPanel: trpc.procedure
    .use(hasRole("admin"))
    .query(() => "Welcome, admin!")
});

Chaining Dynamic Middleware

You can mix and match static middleware (like our logger) with dynamic middleware builders (like our role checker) in the same chain.

This allows for highly flexible and secure API endpoints, where specific logic can be applied based on configuration or runtime values.

type Context = { userId: string | null; userRole: string | null };
const trpc = {
  middleware: (handler: any) => handler,
  procedure: {
    use: (mw: any) => ({
      query: (f: any) => f,
      mutation: (f: any) => f
    }),
    query: (f: any) => f,
    mutation: (f: any) => f
  },
  router: (cfg: any) => cfg,
};

const logMiddleware = trpc.middleware(async ({ path, type, next }) => {
  console.log(`[${type}] Request to ${path} started.`);
  const start = Date.now();
  const result = await next();
  const durationMs = Date.now() - start;
  console.log(`[${type}] Request to ${path} finished in ${durationMs}ms.`);
  return result;
});

const hasRole = (requiredRole: string) => {
  return trpc.middleware(async ({ ctx, next }) => {
    if (!ctx.userRole || ctx.userRole !== requiredRole) {
      throw new Error(`FORBIDDEN: ${requiredRole} role required.`);
    }
    return next();
  });
};

const appRouter = trpc.router({
  adminReport: trpc.procedure
    .use(logMiddleware)
    .use(hasRole("admin"))
    .query(() => "Sensitive admin report data.")
});

Middleware Chain Logic

Consider the following tRPC procedure definition:

// Assume logMiddleware and authMiddleware are defined
// authMiddleware throws if ctx.userId is null
// logMiddleware always calls next()
const myProcedure = trpc.procedure
  .use(logMiddleware)
  .use(authMiddleware)
  .query(({ ctx }) => `Hello ${ctx.userId}`);

If a request comes in with ctx.userId = null, what will happen?

Chains Recap

Great job! You've learned how to build and chain multiple custom middleware in tRPC.

  • Middleware chains allow you to apply multiple layers of logic (logging, authentication, validation) before a procedure executes.
  • The .use() method is used to add middleware, and they run in the order they are defined.
  • The next() function is key to passing control down the chain.
  • Middleware builders can create dynamic, configurable middleware for enhanced reusability.

This powerful pattern helps keep your tRPC API code clean, modular, and robust!

Häufig gestellte Fragen

Ist die Lektion „Benutzerdefinierte Middleware-Ketten“ kostenlos?

Ja — der vollständige Text von „Benutzerdefinierte Middleware-Ketten“ ist hier im Web kostenlos zu lesen. Um sie interaktiv zu üben (integrierter Code-Editor und 24/7 KI-Tutor) und den Rest des tRPC End-to-End Type Safe APIs-Kurses freizuschalten, upgrade auf CoddyKit PRO. Der tRPC End-to-End Type Safe APIs-Kurs umfasst insgesamt 4 Lektionen.

Was lerne ich in „Benutzerdefinierte Middleware-Ketten“?

Erstellen Sie benutzerdefinierte Middleware für Logging, Rate-Limiting oder Autorisierung und verketten Sie diese miteinander. Du übst tRPC End-to-End Type Safe APIs mit praktischem Code, den du direkt im Browser ausführst, und ein 24/7 KI-Tutor beantwortet deine Fragen während du die Lektion bearbeitest.

Brauche ich Erfahrung, um tRPC End-to-End Type Safe APIs zu starten?

Keine Vorkenntnisse erforderlich. tRPC End-to-End Type Safe APIs auf CoddyKit ist für Anfänger bis fortgeschrittene Lernende strukturiert, sodass du hier starten oder von Anfang an beginnen und in deinem eigenen Tempo voranschreiten kannst. Dies ist Lektion 3 von 4.

Wie lange dauert die Lektion „Benutzerdefinierte Middleware-Ketten“?

Die meisten CoddyKit-Lektionen dauern etwa 5–10 Minuten. Jede ist kompakt und interaktiv, sodass du stetig Fortschritte machst und genau dort weitermachst, wo du aufgehört hast – im Web und in der App.

Kann ich in dieser tRPC End-to-End Type Safe APIs-Lektion Code schreiben und ausführen?

Ja. Jede tRPC End-to-End Type Safe APIs-Lektion enthält einen integrierten Code-Editor, sodass du echten Code direkt in deinem Browser schreibst und ausführst und sofort KI-Feedback erhältst — ohne lokale Einrichtung erforderlich.

Alle Lektionen in diesem Kurs

  1. tRPC-Context erstellen
  2. Authentifizierungs-Middleware
  3. Benutzerdefinierte Middleware-Ketten
  4. Middleware für Logging und Laufzeitmessung
← Zurück zu tRPC End-to-End Type Safe APIs