0Pricing
tRPC End-to-End Type Safe APIs · 课时

身份验证中间件

使用 tRPC 中间件实现身份验证检查,以保护 API 过程。

身份验证中间件 是 CoddyKit 上的免费 tRPC End-to-End Type Safe APIs 课时。 这是第 2 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 tRPC End-to-End Type Safe APIs 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 tRPC End-to-End Type Safe APIs 课程共包含 4 节课。

本课时的部分内容尚未翻译,以英文显示。

Protect Your API with Auth

Welcome to this lesson on tRPC authentication middleware! Securing your API is crucial to ensure only authorized users can access sensitive data or perform critical actions.

Middleware in tRPC provides an elegant way to centralize these security checks before any procedure runs.

Why Auth Middleware?

Using middleware for authentication offers significant advantages:

  • Centralized Logic: Define authentication rules once and apply them everywhere.
  • Reduced Duplication: Avoid writing the same security checks in every API procedure.
  • Clean Code: Keep your business logic separate from security concerns.
  • Consistency: Ensure all protected endpoints adhere to the same security standards.

Authentication Basics

Before implementing, let's briefly recall common authentication methods:

  • Tokens: Such as JWTs (JSON Web Tokens) or API keys, typically sent in an Authorization header.
  • Sessions: Often managed with cookies, where the server stores session data and the client sends a session ID.

Our middleware will be responsible for validating these credentials.

Context for User Data

Remember that the tRPC context is an object available to all procedures, carrying request-specific data. For authentication, this means our createContext function (from a previous lesson) should parse incoming authentication information (e.g., from headers) and populate the context with user data if available.

Our middleware will then *read* this user data from the context.

Building Auth Middleware

tRPC's t.middleware() function is where the magic happens. It takes an asynchronous function that receives an object with ctx (the context) and next (a function to call the next middleware or the procedure itself).

Inside, you'll check for authentication. If successful, you call next(). If not, you throw a TRPCError.

Simple Authentication Middleware

Here's a runnable TypeScript example that simulates a basic authentication middleware. It checks if a user object exists in the context.

class TRPCError extends Error {
  code: string;
  constructor(opts: { code: string }) {
    super(`TRPCError: ${opts.code}`);
    this.code = opts.code;
  }
}

type MockContext = { user?: { id: string; name: string } };
type MiddlewareFn = (opts: { ctx: MockContext; next: Function }) => Promise<any>;

const isAuthenticated: MiddlewareFn = async ({ ctx, next }) => {
  if (!ctx.user) {
    throw new TRPCError({ code: 'UNAUTHORIZED' });
  }
  return next({
    ctx: {
      ...ctx,
      user: ctx.user,
    },
  });
};

async function runMiddlewareDemo() {
  console.log("--- Test with authenticated user ---");
  try {
    await isAuthenticated({
      ctx: { user: { id: "123", name: "Alice" } },
      next: async (opts: { ctx: MockContext }) => {
        console.log("Middleware passed. User:", opts.ctx.user?.name);
        return "Success";
      }
    });
  } catch (error) {
    console.error("Error:", error instanceof TRPCError ? error.code : String(error));
  }

  console.log("\n--- Test with unauthenticated user ---");
  try {
    await isAuthenticated({
      ctx: {}, // No user in context
      next: async (opts: { ctx: MockContext }) => {
        console.log("Middleware passed (should not happen)");
        return "Success";
      }
    });
  } catch (error) {
    console.error("Error:", error instanceof TRPCError ? error.code : String(error));
  }
}

runMiddlewareDemo();

Applying Middleware to Procedures

Once defined, you can apply middleware using the .use() method. This can be done on individual procedures or even entire routers to protect multiple procedures at once.

Middleware can also be chained together, allowing you to combine multiple checks (e.g., authentication then authorization).

A Protected Query Example

Here's how you might apply the isAuthenticated middleware to a specific query procedure. The ctx.user will be guaranteed to exist inside the procedure if the middleware passes.

import { t } from './trpc'; // Your tRPC instance
import { isAuthenticated } from './middleware'; // Your auth middleware

// Imagine 'z' is imported for input validation from Zod
// import { z } from 'zod';

const appRouter = t.router({
  publicGreeting: t.procedure
    .query(() => {
      return "Hello, stranger!";
    }),
  
  protectedGreeting: t.procedure
    .use(isAuthenticated) // Apply the middleware here
    .query(({ ctx }) => {
      // ctx.user is guaranteed to exist here due to middleware
      return `Welcome, ${ctx.user.name}! You are authenticated.`;
    }),
});

// This is a conceptual snippet and not runnable standalone.

Handling Unauthorized Access

When the middleware detects an unauthenticated request and throws a TRPCError (e.g., with code: 'UNAUTHORIZED'), tRPC automatically catches this error.

It then sends a standardized error response to the client, allowing your frontend application to gracefully handle the unauthorized access, perhaps by redirecting the user to a login page.

Test Your Auth Middleware Knowledge

You have an isAdmin middleware. You want to protect all procedures within an adminRouter so only administrators can access them. Which is the correct way to apply the middleware?

Authentication Middleware Recap

You've learned how to implement authentication checks using tRPC middleware!

  • Authentication middleware centralizes security logic.
  • It leverages the tRPC context to access user information.
  • You define it using t.middleware().
  • You apply it to procedures or entire routers using .use().
  • TRPCError ensures proper error handling for unauthorized requests.

Next, explore how to build custom middleware chains for more complex scenarios!

常见问题解答

「身份验证中间件」课时是免费的吗?

是的 — 「身份验证中间件」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 tRPC End-to-End Type Safe APIs 课程的其余内容,请升级到 CoddyKit PRO。 tRPC End-to-End Type Safe APIs 课程共包含 4 节课。

「身份验证中间件」这节课中我会学到什么?

使用 tRPC 中间件实现身份验证检查,以保护 API 过程。 你通过在浏览器中直接运行的动手代码来练习 tRPC End-to-End Type Safe APIs,全天候 AI 导师会在你学习这节课的过程中回答你的问题。

学习 tRPC End-to-End Type Safe APIs 需要有经验吗?

无需任何先前经验。CoddyKit 上的 tRPC End-to-End Type Safe APIs 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 2 节课,共 4 节。

「身份验证中间件」课时需要多长时间?

大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。

我能在这节 tRPC End-to-End Type Safe APIs 课中编写并运行代码吗?

能。每节 tRPC End-to-End Type Safe APIs 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。

此课程中的所有课时

  1. 创建 tRPC 上下文
  2. 身份验证中间件
  3. 自定义中间件链
  4. 日志记录与性能计时中间件
← 返回 tRPC End-to-End Type Safe APIs