사용자 지정 미들웨어 연결
로깅, 요청 빈도 제한 또는 권한 부여를 위한 사용자 지정 미들웨어를 만들고 서로 연결합니다.
사용자 지정 미들웨어 연결은(는) CoddyKit의 무료 tRPC End-to-End Type Safe APIs 강의입니다. 이것은 4개 중 3번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 tRPC End-to-End Type Safe APIs 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. tRPC End-to-End Type Safe APIs 강의에는 총 4개의 강의가 포함되어 있습니다.
이 강의의 일부는 아직 번역되지 않았으며 영어로 표시됩니다.
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:
logMiddlewareruns first.- If
logMiddlewarecallsnext(), thenisAuthenticatedruns. - If
isAuthenticatedcallsnext(), then the actualqueryprocedure handler runs. - 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!
자주 묻는 질문
“사용자 지정 미들웨어 연결” 강의는 무료인가요?
네 — “사용자 지정 미들웨어 연결” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 tRPC End-to-End Type Safe APIs 강의 전체를 잠금 해제할 수 있습니다. tRPC End-to-End Type Safe APIs 강의에는 총 4개의 강의가 포함되어 있습니다.
“사용자 지정 미들웨어 연결”에서 뭘 배우나요?
로깅, 요청 빈도 제한 또는 권한 부여를 위한 사용자 지정 미들웨어를 만들고 서로 연결합니다. 브라우저에서 직접 실행하는 실습 코드로 tRPC End-to-End Type Safe APIs을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.
tRPC End-to-End Type Safe APIs을(를) 시작하는 데 경험이 필요한가요?
사전 경험은 필요하지 않습니다. CoddyKit의 tRPC End-to-End Type Safe APIs은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 3번째 강의입니다.
“사용자 지정 미들웨어 연결” 강의는 얼마나 걸리나요?
대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.
이 tRPC End-to-End Type Safe APIs 강의에서 코드를 작성하고 실행할 수 있나요?
네. 모든 tRPC End-to-End Type Safe APIs 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.
이 강의의 모든 강의
- tRPC 컨텍스트 만들기
- 인증 미들웨어
- 사용자 지정 미들웨어 연결
- 로깅 및 성능 측정 미들웨어