如何隐藏 nextjs API 路由以防止通过 URL 直接访问?

Shi*_*odi 8 javascript security next.js

有没有办法让 next.js API 在通过 URL 访问时隐藏路由响应数据?我想隐藏路线,因为有些数据我不想被用户直接访问。

小智 9

在 Next.js 版本 13 中,您可以使用中间件通过检查 req.referer 来阻止用户直接检查 api 的路由,然后只有您的应用程序可以调用您的应用程序的 api。身份验证令牌也可以在中间件内部使用。

https://nextjs.org/blog/next-13-1#nextjs-advanced-middleware

import { NextResponse } from 'next/server'

import type { NextRequest } from 'next/server'

export function middleware(req: NextRequest) {

    const url = req.nextUrl
    const { pathname } = url

    if (pathname.startsWith(`/api/`)) {
        if (!req.headers.get("referer")?.includes(process.env.APP_URL as string)) {
        return NextResponse.json({ message: 'Unauthorized' }, { status: 401 });
        }
      }

     return NextResponse.next()

}

export const config = {
  matcher: ['/((?!_next|fonts|examples|svg|[\\w-]+\\.\\w+).*)'],
}
Run Code Online (Sandbox Code Playgroud)

process.env.APP_URL 是您的应用程序的 url,例如:http://localhost:3000


Shi*_*odi 1

nextjs 中无法通过 url 向用户隐藏 API 路由。事实上,当您托管网站时,任何人都可以公开使用 nextjs API 路由,而无需从外部文件夹导出和托管。我结束了使用 Node Express 制作服务器端路由,然后连接到 nextjs 中的前端。