มิดเดิลแวร์การตรวจสอบสิทธิ์
ใช้งานการตรวจสอบสิทธิ์ด้วยมิดเดิลแวร์ของ tRPC เพื่อปกป้องกระบวนงาน API
มิดเดิลแวร์การตรวจสอบสิทธิ์ เป็นบทเรียน tRPC End-to-End Type Safe APIs ฟรีบน CoddyKit นี่คือบทเรียนที่ 2 จากทั้งหมด 4 บทเรียน คุณสามารถอ่านบทเรียนทั้งหมดด้านล่างฟรี — จากนั้นลองปฏิบัติด้วยตัวคุณเองในเบราว์เซอร์พร้อมตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7 บทเรียนนี้เป็นส่วนหนึ่งของเส้นทางการเรียน 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
Authorizationheader. - 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(). TRPCErrorensures proper error handling for unauthorized requests.
Next, explore how to build custom middleware chains for more complex scenarios!
คำถามที่พบบ่อย
บทเรียน “มิดเดิลแวร์การตรวจสอบสิทธิ์” ฟรีหรือไม่
ใช่ — ข้อความเต็มของ “มิดเดิลแวร์การตรวจสอบสิทธิ์” ฟรีให้อ่านที่นี่บนเว็บ เพื่อปฏิบัติแบบโต้ตอบ (ตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7) และปลดล็อคส่วนที่เหลือของคอร์ส 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 ตลอด 24/7 ตอบคำถามของคุณขณะที่คุณไปผ่านบทเรียน
คุณต้องมีประสบการณ์ก่อนที่จะเริ่มเรียน tRPC End-to-End Type Safe APIs หรือไม่
ไม่จำเป็นต้องมีประสบการณ์มาก่อน tRPC End-to-End Type Safe APIs บน CoddyKit ออกแบบมาสำหรับผู้เริ่มต้นไปจนถึงผู้เรียนขั้นสูง คุณสามารถเริ่มต้นที่นี่หรือเริ่มจากตัวแรกและเรียนด้วยความเร็วของคุณเอง นี่คือบทเรียนที่ 2 จากทั้งหมด 4 บทเรียน
บทเรียน “มิดเดิลแวร์การตรวจสอบสิทธิ์” ใช้เวลานานแค่ไหน
บทเรียน CoddyKit ส่วนใหญ่ใช้เวลาประมาณ 5–10 นาที แต่ละบทเรียนจึงสั้นและเป็นแบบโต้ตอบ คุณสามารถก้าวหน้าอย่างต่อเนื่องและกลับมาเรียนต่อจากตรงที่เพิ่งหยุดบนเว็บและแอปได้เลย
ฉันเขียนและรันโค้ดในบทเรียน tRPC End-to-End Type Safe APIs นี้ได้ไหม
ได้ บทเรียน tRPC End-to-End Type Safe APIs ทุกบทมีตัวแก้ไขโค้ดในตัว คุณจึงเขียนและรันโค้ดจริงได้เลยในเบราว์เซอร์ และได้รับข้อเสนอแนะจาก AI ในทันที — ไม่ต้องติดตั้งในเครื่องของคุณ
บทเรียนทั้งหมดในหลักสูตรนี้
- การสร้างบริบท tRPC
- มิดเดิลแวร์การตรวจสอบสิทธิ์
- สายโซ่มิดเดิลแวร์แบบกำหนดเอง
- มิดเดิลแวร์สำหรับบันทึกและจับเวลาประสิทธิภาพ