0Pricing
tRPC End-to-End Type Safe APIs · 강의

인증 미들웨어

tRPC 미들웨어를 사용하여 인증을 확인하고 API 절차를 보호합니다.

인증 미들웨어은(는) CoddyKit의 무료 tRPC End-to-End Type Safe APIs 강의입니다. 이것은 4개 중 2번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 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!

자주 묻는 질문

“인증 미들웨어” 강의는 무료인가요?

네 — “인증 미들웨어” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 tRPC End-to-End Type Safe APIs 강의 전체를 잠금 해제할 수 있습니다. tRPC End-to-End Type Safe APIs 강의에는 총 4개의 강의가 포함되어 있습니다.

“인증 미들웨어”에서 뭘 배우나요?

tRPC 미들웨어를 사용하여 인증을 확인하고 API 절차를 보호합니다. 브라우저에서 직접 실행하는 실습 코드로 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개 중 2번째 강의입니다.

“인증 미들웨어” 강의는 얼마나 걸리나요?

대부분의 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(으)로 돌아가기