0Pricing
Next.js 15 Fullstack Web Apps · 강의

미들웨어와 접근 제어

Next.js 미들웨어를 사용하여 인증 및 리디렉션을 위한 경로와 API 엔드포인트를 보호합니다.

미들웨어와 접근 제어은(는) CoddyKit의 무료 Next.js 15 Fullstack Web Apps 강의입니다. 이것은 4개 중 3번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 Next.js 15 Fullstack Web Apps 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. Next.js 15 Fullstack Web Apps 강의에는 총 4개의 강의가 포함되어 있습니다.

이 강의의 일부는 아직 번역되지 않았으며 영어로 표시됩니다.

Intercepting Requests with Middleware

Welcome to Lesson 3! In this lesson, we'll explore Next.js Middleware. Think of middleware as a gatekeeper for your application.

It allows you to run code before a request is completed, letting you inspect, modify, or even redirect requests based on certain conditions. This is super useful for access control!

Creating Your First Middleware

To create middleware, you simply add a middleware.ts (or .js) file at the root of your project, or inside the src directory.

This file must export a default function that takes a NextRequest object and returns a NextResponse. Let's create a basic one:

import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';

export function middleware(request: NextRequest) {
  console.log('Middleware is running!');
  // Continue to the requested page
  return NextResponse.next();
}

Basic Redirection for Access Control

A common use case for middleware is to protect routes. For example, you might want to redirect users who aren't logged in away from a dashboard page.

Here, we'll simulate checking for an 'auth_token' cookie. If it's missing, we redirect the user to the homepage.

import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';

export function middleware(request: NextRequest) {
  const isAuthenticated = request.cookies.has('auth_token');
  const { pathname } = request.nextUrl;

  // If not authenticated and trying to access /dashboard
  if (!isAuthenticated && pathname.startsWith('/dashboard')) {
    console.log('User not authenticated, redirecting...');
    return NextResponse.redirect(new URL('/', request.url));
  }

  return NextResponse.next();
}

Defining Middleware Scope with `matcher`

By default, middleware runs on every request. This isn't always efficient. You can specify which paths your middleware should run on using the config.matcher property.

The matcher is an array of strings that define path patterns. It's more powerful and recommended than conditional logic inside the middleware function for path filtering.

Using `matcher` for Specific Paths

Let's update our middleware to only run on paths that start with /dashboard or /profile. This makes our middleware more performant by not running on unnecessary routes.

  • /dashboard/:path* matches /dashboard and any sub-paths like /dashboard/settings.
  • /profile/:path* matches /profile and its sub-paths.
import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';

export function middleware(request: NextRequest) {
  const isAuthenticated = request.cookies.has('auth_token');

  if (!isAuthenticated) {
    console.log('Not authenticated, redirecting to home.');
    return NextResponse.redirect(new URL('/', request.url));
  }

  return NextResponse.next();
}

export const config = {
  matcher: ['/dashboard/:path*', '/profile/:path*'],
};

Reading & Modifying Request Headers

Middleware can also read and modify request headers. This is useful for passing information down to your pages or API routes, or for adding security headers.

The NextRequest object provides methods to interact with headers, cookies, and the URL.

import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';

export function middleware(request: NextRequest) {
  const requestHeaders = new Headers(request.headers);
  const userAgent = requestHeaders.get('user-agent');
  console.log('User-Agent:', userAgent);

  // Add a custom header
  requestHeaders.set('x-custom-header', 'Hello from Middleware');

  // Return a new response with modified headers
  return NextResponse.next({
    request: { headers: requestHeaders },
  });
}

Protecting API Routes with Middleware

Middleware applies to all routes in your application, including API routes (e.g., /api/users). This is a powerful feature for implementing API authentication and authorization.

You can check for API keys, JWTs, or session tokens in the request headers or cookies before allowing access to your API endpoints.

Authorization vs. Authentication

It's important to distinguish between Authentication (AuthN) and Authorization (AuthZ):

  • Authentication: Verifies who a user is (e.g., by checking their login credentials).
  • Authorization: Determines what an authenticated user is allowed to do (e.g., access admin pages, delete content).

Middleware can enforce both, by checking if a user is logged in (AuthN) and if they have the necessary roles/permissions (AuthZ) before granting access to a route.

Advanced Authorization Example

Let's combine concepts for a more advanced scenario: checking for an 'admin' role. We'll simulate reading a user role from a cookie and redirecting non-admin users from an /admin path.

This shows how middleware acts as a central point for access control logic.

import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';

export function middleware(request: NextRequest) {
  const userRole = request.cookies.get('user_role')?.value;
  const { pathname } = request.nextUrl;

  // If trying to access /admin routes
  if (pathname.startsWith('/admin')) {
    // Check if user has 'admin' role
    if (userRole !== 'admin') {
      console.log('Access denied: User is not an admin, redirecting.');
      return NextResponse.redirect(new URL('/unauthorized', request.url));
    }
  }

  return NextResponse.next();
}

export const config = {
  matcher: ['/admin/:path*'],
};

Middleware Matching Challenge

Consider the following config.matcher. Which of these paths WILL be processed by the middleware?

export const config = {
  matcher: ['/dashboard/:path*', '/settings'],
};

Recap: Middleware for Control

You've learned how Next.js Middleware acts as a powerful interceptor for incoming requests.

  • It's defined in a middleware.ts file.
  • It can redirect users, modify requests/responses, and add headers.
  • The config.matcher is essential for defining which routes your middleware should protect.
  • It's crucial for implementing both authentication and authorization logic across your application, including API routes.

Middleware gives you fine-grained control over access and behavior!

자주 묻는 질문

“미들웨어와 접근 제어” 강의는 무료인가요?

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

“미들웨어와 접근 제어”에서 뭘 배우나요?

Next.js 미들웨어를 사용하여 인증 및 리디렉션을 위한 경로와 API 엔드포인트를 보호합니다. 브라우저에서 직접 실행하는 실습 코드로 Next.js 15 Fullstack Web Apps을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.

Next.js 15 Fullstack Web Apps을(를) 시작하는 데 경험이 필요한가요?

사전 경험은 필요하지 않습니다. CoddyKit의 Next.js 15 Fullstack Web Apps은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 3번째 강의입니다.

“미들웨어와 접근 제어” 강의는 얼마나 걸리나요?

대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.

이 Next.js 15 Fullstack Web Apps 강의에서 코드를 작성하고 실행할 수 있나요?

네. 모든 Next.js 15 Fullstack Web Apps 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.

이 강의의 모든 강의

  1. NextAuth.js 통합
  2. 세션 관리와 JWT
  3. 미들웨어와 접근 제어
  4. 역할 기반 액세스 제어(RBAC)
← Next.js 15 Fullstack Web Apps(으)로 돌아가기