0Pricing
Next.js 15 Fullstack Web Apps · 课时

中间件与访问控制

使用 Next.js 中间件保护路由和 API 端点,实现授权与重定向。

中间件与访问控制 是 CoddyKit 上的免费 Next.js 15 Fullstack Web Apps 课时。 这是第 3 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 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!

常见问题解答

「中间件与访问控制」课时是免费的吗?

是的 — 「中间件与访问控制」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 Next.js 15 Fullstack Web Apps 课程的其余内容,请升级到 CoddyKit PRO。 Next.js 15 Fullstack Web Apps 课程共包含 4 节课。

「中间件与访问控制」这节课中我会学到什么?

使用 Next.js 中间件保护路由和 API 端点,实现授权与重定向。 你通过在浏览器中直接运行的动手代码来练习 Next.js 15 Fullstack Web Apps,全天候 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