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

未授权时如何在Middleware中为当前URL添加搜索参数?

解决方案

你当前的代码会直接重定向到根路径加授权弹窗参数,要实现在当前访问的URL后添加?modal=auth,需要基于当前请求的URL来构建重定向目标,而不是固定跳转到根目录。

修改后的Middleware代码如下:

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

export async function middleware(req: NextRequest) {
  const token = req.cookies.get("session")?.value || "";
  const res = await fetch(`${process.env.HOST}/api/user/me`, {
    headers: {
      cookie: `session=${token}`,
    },
  });

  if (!token || res.status === 403) {
    // 复制当前请求的URL对象,保留原路径与已有参数
    const redirectUrl = req.nextUrl.clone();
    // 添加或覆盖modal参数为auth
    redirectUrl.searchParams.set("modal", "auth");
    // 重定向到修改后的当前URL
    return NextResponse.redirect(redirectUrl);
  }

  return NextResponse.next();
}

export const config = {
  matcher: [
    "/my",
    "/bookmarks",
    "/new"
  ],
};

关键修改说明:

  • 用req.nextUrl.clone()复制当前URL实例,避免修改原请求的URL对象
  • 通过searchParams.set()添加授权弹窗参数,原URL的其他查询参数会被保留
  • 重定向目标改为修改后的当前URL,而非固定根路径

比如用户访问http://localhost/article/1时,重定向后会变为http://localhost/article/1?modal=auth;若原URL已有参数如http://localhost/article/1?sort=hot,则会生成http://localhost/article/1?sort=hot&modal=auth。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.13 19:14:56