Next.js (Middleware)
Next.js Middleware 运行在 Edge 边缘运行时,这意味着它在请求到达您的标准 API 路由、Server Actions 或数据库之前,就在极其靠近用户的位置执行。这是阻断恶意流量的最优关卡。
中间件实现
此实现利用原生的 NextRequest 对象可靠提取客户端 IP。它借助轻量级的 Edge Runtime 调用 ProxyTracer API,并严格执行 500ms 超时限制,确保页面加载体验始终保持极速。
// middleware.ts
import { NextResponse } from 'next/server'
import type { NextRequest } from 'next/server'
export async function middleware(request: NextRequest) {
// 1. 提取 IP(Next.js 会在 Vercel/Edge 上安全地填充 request.ip)
// 若在自定义反向代理后自建托管,则回退读取请求头
const ip = request.ip || request.headers.get('x-forwarded-for')?.split(',')[0].trim()
// 若为本地开发环境则直接放行
if (!ip || ip === '127.0.0.1' || ip === '::1') {
return NextResponse.next()
}
try {
// 2. 使用原生 fetch 查询 ProxyTracer API(配置严格超时)
const ptResponse = await fetch(`https://api.proxytracer.com/v1/check/${ip}`, {
method: 'GET',
headers: {
'Authorization': `Bearer ${process.env.PROXYTRACER_API_KEY}`
},
signal: AbortSignal.timeout(500) // 若请求耗时超过 500ms 则直接中断连接
})
if (ptResponse.ok) {
const data = await ptResponse.json()
// 3. 若检测到代理/VPN,立即丢弃连接
if (data.proxy === true) {
return NextResponse.json(
{ error: "Access Denied: VPN or Proxy detected." },
{ status: 403 }
)
}
}
} catch (error) {
// 故障开放(Fail-open):若 API 超时,放行流量以确保可用性
console.error('ProxyTracer API Error:', error)
}
// 4. 流量正常,继续访问请求的页面或 API 路由
return NextResponse.next()
}
// 5. 配置匹配器(Matcher)
// 将此中间件应用于敏感路由,或保持全局生效以保护全站
export const config = {
matcher: [
/*
* Match all request paths except for the ones starting with:
* - _next/static (static files)
* - _next/image (image optimization files)
* - favicon.ico (favicon file)
*/
'/((?!_next/static|_next/image|favicon.ico).*)',
],
}Vercel 部署提示:如果您部署在 Vercel 平台,request.ip 保证为真实客户端 IP。除非您在自定义的 Node/Docker 基础设施上自建反向代理,否则无需手动解析代理请求头。
最后更新于