一座群岛展馆,一定有统一入岛逻辑:
- 看 cookie
- 看身份
- 写 request 级上下文
- 做重写或拦截
- 统一加响应头
这就是 middleware 的位置。
// src/middleware.ts
import { defineMiddleware } from 'astro:middleware';
export const onRequest = defineMiddleware(async (context, next) => {
const session = context.cookies.get('session')?.value;
context.locals.user = session
? await findUserBySession(session)
: null;
return next();
});然后在页面里读取:
---
const user = Astro.locals.user;
---
<header>
{user ? `欢迎回来,${user.name}` : '你好,陌生游客'}
</header>这条链路的关键心智是:
middleware 写入 context.locals
页面和 endpoint 通过 Astro.locals / context.locals 读取而且 locals 是请求级的。
它不是全局共享仓库,不应该被误当成跨请求常驻状态。
这点非常重要。