You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

NextJS中间件请求NestJS后端无Cookie传递问题求助

问题:NextJS中间件请求无法传递Cookie到NestJS后端

用NextJS做前端框架、NestJS做后端框架,校验会话ID有效性时,通过NextJS中间件发送请求到后端,请求能正常抵达,但后端通过req.cookies获取到的结果是空对象[Object: null prototype] {};而从首页这类普通页面发送完全相同的请求时,Cookie能正常传递,推测问题出在NextJS中间件中。

相关代码

NextJS中间件代码

// middleware.ts
import type { NextRequest } from "next/server";

export function middleware(request: NextRequest) {
  if (request.cookies.has("userData")) {
    let cookie = request.cookies.get("userData");

    console.log(cookie);

    fetch(new URL("/authentication/check-auth", "http://localhost:5000"), {
      method: "GET",
      headers: {
        Accept: "application/json",
        "Content-Type": "application/json",
      },
      credentials: "include",
    })
      .then((resp) => resp.json())
      .then((data) => {
        console.log(data);
      })
      .catch((err) => {
        console.log(err);
      });
  }
}

export const config = {
  matcher: ["/((?!api|_next/static|_next/image|favicon.ico).*)"]
};

NestJS main.ts代码

import { NestFactory } from "@nestjs/core";
import { AppModule } from "./app.module";
import helmet from "helmet";
import * as cookieParser from "cookie-parser";

async function bootstrap() {
  const app = await NestFactory.create(AppModule);
  const corsOptions: any = {
    origin: "http://localhost:3000",
    credentials: true,
  };
  app.use(cookieParser());
  app.enableCors(corsOptions);
  app.use(helmet());
  await app.listen(5000);
}
bootstrap();

NestJS Controller代码

@Get("check-auth")
async checkAuth(@Req() req: Request) {
  try {
    const cookies = req.cookies;
    console.log("Cookies:", cookies); // 输出:Cookies: [Object: null prototype] {}

    const result = await this.authenticationService.checkAuth(cookies);

    return result;
  } catch (error) {
    console.error("Error:", error);
    return { error: "An error occurred" };
  }
}

NestJS Service代码

async checkAuth(sessionID: any) {
  const exists = await this.redisClient.exists(sessionID.userData);
  console.log(exists);
  return exists === 1;
}

浏览器Cookie截图:
浏览器Cookie截图

解决方案

问题根源是NextJS中间件运行在服务器端,此时credentials: "include"无法自动携带当前请求的Cookie——服务器端环境没有浏览器的Cookie上下文,必须手动把Cookie添加到请求头中。

修改后的NextJS中间件代码如下:

// middleware.ts
import type { NextRequest } from "next/server";

export function middleware(request: NextRequest) {
  if (request.cookies.has("userData")) {
    // 从当前请求头中获取完整的Cookie字符串
    const cookieHeader = request.headers.get('cookie');

    fetch(new URL("/authentication/check-auth", "http://localhost:5000"), {
      method: "GET",
      headers: {
        Accept: "application/json",
        "Content-Type": "application/json",
        // 手动设置Cookie请求头
        Cookie: cookieHeader || '',
      },
      // 服务器端请求无需设置credentials选项
    })
      .then((resp) => resp.json())
      .then((data) => {
        console.log(data);
      })
      .catch((err) => {
        console.log(err);
      });
  }
}

export const config = {
  matcher: ["/((?!api|_next/static|_next/image|favicon.ico).*)"]
};

关键说明

  • NextJS中间件默认在服务器端执行,无法依赖浏览器的credentials机制自动传Cookie,必须手动提取并设置Cookie请求头。
  • 直接从request.headers.get('cookie')获取完整Cookie字符串,比单独拼接单个Cookie更可靠,能保证所有相关Cookie都被传递。
  • 服务器端发起的fetch请求不需要设置credentials: "include",这个选项仅针对浏览器环境的跨域请求。

内容的提问来源于stack exchange,提问作者PauloRamos

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.10 04:55:58