在服务器操作中读取cookie时遇到问题,如何确保cookie存在?下一页13

Trouble reading the cookie in server action, how to ensure that cookie is present? Next13

提问人:Kerem Aydemir 提问时间:11/11/2023 更新时间:11/11/2023 访问量:12

问:

我需要授权令牌才能成功获取 API。如果 cookie 中不存在此令牌,我需要先发出获取请求并设置带有响应的 cookie。我在“middleware.ts”中将此令牌设置为 cookie,并在连接到所有其他服务器操作的服务器操作中读取该 cookie。问题是cookie已经设置好了,我在应用程序选项卡中看到了它,但我无法在服务器操作中正确读取它。如何确保令牌存在?我需要确保所有获取调用都具有该授权标头。

我已经尝试了带有 Set-Cookie 标头的 next.config.js 中的标头对象,它的结果与中间件相同。

middleware.ts

import { NextResponse, type NextRequest } from "next/server"

import makeHandshake from "./services/auth/handshake"

const HS_TOKEN_NAME = process.env.HS_TOKEN_NAME!

export async function middleware(req: NextRequest): Promise<NextResponse> {
  const res = NextResponse.next()
  const token = req.cookies.get(HS_TOKEN_NAME)?.value

  if (!token) {
    const newToken = await makeHandshake()
    res.cookies.set(HS_TOKEN_NAME, newToken)
  }

  return res
}

export const config = {}
export default async function getServerDefaults(
  options: Options | undefined = undefined
): Promise<ServerDefaults> {
  const baseURL = process.env.NEXT_PUBLIC_API_BASE_URL!;
  const HS_TOKEN_NAME = process.env.HS_TOKEN_NAME!;

  let token = cookies().get(HS_TOKEN_NAME)?.value;
  console.log("token first", token);

  function sleep(ms: number): Promise<void> {
    return new Promise((resolve) => {
      setTimeout(resolve, ms);
    });
  }

  if (!token) await sleep(2000);
  // cookie is present in application tab but it doesn't read it
  // sleep works as expected all requests wait for 2 seconds, no problem there
  token = cookies().get(HS_TOKEN_NAME)?.value; // still no value

  let defaultHeaders = {
    "Content-Type": "application/json",
    Accept: "application/json",
    Authorization: `Bearer ${token}`,
  };

  if (options?.scope) {
    defaultHeaders = Object.assign(defaultHeaders, {
      "x-ob-scope": options.scope,
    });
  }

  const headers = new Headers(defaultHeaders);

  return { headers, baseURL };
}

console.log(“令牌优先”,令牌)生成:

  some actions gets the token but not all of them

  token first undefined
  token first undefined
  token first undefined
  token first undefined
  token first undefined
  token first undefined
  token first undefined
  token first token123
  token first token123
Cookie 中间件 服务器操作

评论


答: 暂无答案