0Pricing
Next.js 15 Fullstack Web Apps · レッスン

ミドルウェアとアクセス制御

Next.js Middlewareを使用して、認可とリダイレクトによりルートとAPIエンドポイントを保護します。

「ミドルウェアとアクセス制御」はCoddyKit上の無料Next.js 15 Fullstack Web Appsレッスンです。 これはレッスン3/4です。 下記で完全なレッスンを無料で読むことができます。その後、ブラウザ内の組み込みコードエディタと24時間対応の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時間対応のAIチューター)、Next.js 15 Fullstack Web Appsコースの残りをアンロックするには、CoddyKit PROにアップグレードしてください。 Next.js 15 Fullstack Web Appsコースには全4レッスンが含まれています。

「ミドルウェアとアクセス制御」で何を学びますか?

Next.js Middlewareを使用して、認可とリダイレクトによりルートとAPIエンドポイントを保護します。 ブラウザで直接実行するハンズオンコードでNext.js 15 Fullstack Web Appsを演習し、24時間対応のAIチューターがレッスンを進める中での質問に答えます。

Next.js 15 Fullstack Web Appsを始めるのに経験は必要ですか?

事前経験は必要ありません。CoddyKitのNext.js 15 Fullstack Web Appsは初級者から上級者向けに構成されているため、ここから始めるか最初から始めて、自分のペースで進むことができます。 これはレッスン3/4です。

「ミドルウェアとアクセス制御」レッスンにはどのくらい時間がかかりますか?

ほとんどの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に戻る