有没有办法让Next JS API只响应来自前端的请求?使用Next 13

4smxwvx5  于 2023-06-29  发布在  其他
关注(0)|答案(1)|浏览(66)

我想阻止任何其他的api,以便能够访问我的一个NEXT API端点。有办法在NEXT 13中配置吗?我正在使用基于应用程序的目录和新的NEXT 13功能。
下面是一个例子:

// This code is added in one of the client components
useEffect(() => {
        cacheFetch(apiRoutes.GET_TOKEN, { noCache: true }).then((result) => {
            console.log('Result = ', result);
        });
    }, []);

下面是@Yilmaz建议的中间件:

import { NextRequest, NextResponse } from 'next/server';
enum MiddlewareRoutes {
    GET_TOKEN = '/api/get-token',
}

const middlewareHandler = async (
    route: MiddlewareRoutes,
    request: NextRequest,
    response: NextResponse
): Promise<NextResponse> => {
    switch (route) {
        case MiddlewareRoutes.GET_TOKEN: {
            const fromFE = request.nextUrl.pathname.startsWith('/api');
            console.log('From Frontent = ', fromFE);
            return response;
        }
        default: {
            return response;
        }
    }
};

export async function middleware(request: NextRequest) {
    const response = NextResponse.next();
    const newResponse = await middlewareHandler(
        (request?.nextUrl?.pathname ?? '') as MiddlewareRoutes,
        request,
        response
    );
    return newResponse;
}

export const config = {
    matcher: ['/api/:path*'],
};

现在预期的结果是:curl http://localhost:3000/api/get-token应记录:From Frontent = false,useEffect块发送请求时应记录:从Frontent = true
但在这两种情况下,它都返回true。有人能帮我在这里使中间件fromFrontend变量假时,它来自我的NEXT JS前端?
我不想注入一个查询参数,除非它被内部注入,否则它可能会被欺骗。

nx7onnlm

nx7onnlm1#

export async function middleware(req: NextRequest) {
  const response = NextResponse.next()

  if (req.nextUrl.pathname.startsWith("/api")) {
    response.headers.append("Access-Control-Allow-Origin", "yourDomainHere")
  }
  
  return response
}

相关问题