全书目录

第五篇:Next.js 完全指南 —— 商业综合体宇宙

第十二章:proxy.ts —— 门禁、分流、入口检查

1 分钟 109 字 第 123 / 962 个阅读单元

在当前官方文档体系里,这层入口逻辑使用 proxy.ts

tsx
// proxy.ts
import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';

export function proxy(request: NextRequest) {
  const isDashboard = request.nextUrl.pathname.startsWith('/dashboard');
  const hasSession = request.cookies.has('session');

  if (isDashboard && !hasSession) {
    return NextResponse.redirect(new URL('/login', request.url));
  }

  return NextResponse.next();
}

它适合做的事:

  • 简单门禁
  • 路径分流
  • 入口级判断

不适合做的事:

  • 很慢的数据库查询
  • 整套复杂业务编排
  • 把所有后端逻辑都堆在入口层

门禁是门禁,后厨是后厨,别混。