From 50f5fbd1222b756b44acfa38b7c8cac3a2136101 Mon Sep 17 00:00:00 2001 From: Timothy Yin Date: Thu, 12 Mar 2026 09:41:57 +0800 Subject: [PATCH] refactor(middleware): improve isInitialized function and cookie handling --- apps/web/middleware.ts | 32 +++++++++++++++++++------------- 1 file changed, 19 insertions(+), 13 deletions(-) diff --git a/apps/web/middleware.ts b/apps/web/middleware.ts index 21fc99e..9b3c6f9 100644 --- a/apps/web/middleware.ts +++ b/apps/web/middleware.ts @@ -1,16 +1,19 @@ import { NextRequest, NextResponse } from "next/server"; const CSMS_INTERNAL_URL = - process.env.CSMS_INTERNAL_URL ?? - process.env.NEXT_PUBLIC_CSMS_URL ?? - "http://localhost:3001"; + process.env.CSMS_INTERNAL_URL ?? process.env.NEXT_PUBLIC_CSMS_URL ?? "http://localhost:3001"; /** 检查 CSMS 是否已完成初始化(有用户存在)。使用 cookie 缓存结果,避免每次请求都查询。 */ -async function isInitialized(request: NextRequest): Promise<{ initialized: boolean; fromCache: boolean }> { - // 读缓存 cookie - const cached = request.cookies.get("helios_setup_done"); - if (cached?.value === "1") { - return { initialized: true, fromCache: true }; +async function isInitialized( + request: NextRequest, + useCache = true, +): Promise<{ initialized: boolean; fromCache: boolean }> { + // 读缓存 cookie(仅在 useCache=true 时使用,避免 DB 重置后缓存陈旧) + if (useCache) { + const cached = request.cookies.get("helios_setup_done"); + if (cached?.value === "1") { + return { initialized: true, fromCache: true }; + } } try { @@ -66,25 +69,28 @@ export async function middleware(request: NextRequest) { const fromPath = request.nextUrl.search ? pathname + request.nextUrl.search : pathname; loginUrl.searchParams.set("from", fromPath); const res = NextResponse.redirect(loginUrl); - if (!fromCache) res.cookies.set("helios_setup_done", "1", { path: "/", httpOnly: true, sameSite: "lax" }); + if (!fromCache) + res.cookies.set("helios_setup_done", "1", { path: "/", httpOnly: true, sameSite: "lax" }); return res; } const res = NextResponse.next(); - if (!fromCache) res.cookies.set("helios_setup_done", "1", { path: "/", httpOnly: true, sameSite: "lax" }); + if (!fromCache) + res.cookies.set("helios_setup_done", "1", { path: "/", httpOnly: true, sameSite: "lax" }); return res; } - // /login 路由:未初始化则跳转 /setup + // /login 路由:未初始化则跳转 /setup(不使用缓存,防止 DB 重置后缓存陈旧) if (pathname === "/login") { - const { initialized, fromCache } = await isInitialized(request); + const { initialized, fromCache } = await isInitialized(request, false); if (!initialized) { const res = NextResponse.redirect(new URL("/setup", request.url)); if (!fromCache) res.cookies.delete("helios_setup_done"); return res; } const res = NextResponse.next(); - if (!fromCache) res.cookies.set("helios_setup_done", "1", { path: "/", httpOnly: true, sameSite: "lax" }); + if (!fromCache) + res.cookies.set("helios_setup_done", "1", { path: "/", httpOnly: true, sameSite: "lax" }); return res; }