You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Next.js中间件问题:取消注释某行后页面丢失CSS与JS交互

Next.js中间件导致页面丢失样式与交互的原因及修复

问题原因

你的中间件规则未排除静态资源请求。Next.js的CSS、JS等静态资源默认存放在/_next/static/路径下,当用户未登录时,这些静态资源的请求会被中间件判定为「非公开路径」,进而被重定向到/login页面。页面无法加载到所需的样式和脚本,自然就失去了样式和交互能力。

修复方案

方案1:在逻辑中排除静态资源路径

修改isPublic的判断条件,将静态资源路径和网站图标加入公开路径列表:

import { NextRequest, NextResponse } from "next/server";

export function middleware(request) {
  const path = request.nextUrl.pathname;
  const token = request.cookies.get("token")?.value || "";
  // 包含公开页面、静态资源和网站图标
  const isPublic = path === "/signup" || 
                  path === "/login" || 
                  path.startsWith("/_next/static/") || 
                  path.startsWith("/_next/image/") ||
                  path === "/favicon.ico";
  const response = NextResponse.next();

  if (!token && !isPublic) {
    return NextResponse.redirect(new URL("/login", request.url));
  }
  // 已登录时,仅对公开业务页面重定向,跳过静态资源
  if (token && isPublic && !path.startsWith("/_next/") && path !== "/favicon.ico") {
    return NextResponse.redirect(new URL("/profile", request.url));
  }
  return response;
}

方案2:通过config指定中间件匹配范围(更简洁)

添加config配置,让中间件只拦截业务页面,自动忽略静态资源路径:

import { NextRequest, NextResponse } from "next/server";

export function middleware(request) {
  const path = request.nextUrl.pathname;
  const token = request.cookies.get("token")?.value || "";
  const isPublic = path === "/signup" || path === "/login";
  const response = NextResponse.next();

  if (!token && !isPublic) {
    return NextResponse.redirect(new URL("/login", request.url));
  }
  if (token && isPublic) {
    return NextResponse.redirect(new URL("/profile", request.url));
  }
  return response;
}

// 指定中间件仅匹配非静态资源路径
export const config = {
  matcher: [
    '/((?!_next/static|_next/image|favicon.ico).*)',
  ],
};

说明

方案2通过matcher配置直接限定中间件的作用范围,避免了在业务逻辑中处理静态资源的判断,代码更简洁易维护。两种方案都能解决静态资源被错误重定向的问题,恢复页面的样式和交互能力。

内容的提问来源于stack exchange,提问作者farid lord

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.13 21:15:14