NextJS 中间件只能在开发期间获取 httpOnly cookie?

问题描述 投票:0回答:2

使用 NextJS _middleware.js 时,它会在本地主机中的开发过程中获取 cookie,但是一旦我部署到 vercel 上,它就会停止获取 cookie。 Cookie 是 httpOnly,并且 Cookie 存在于网站上,但生产中的中间件不会获取该 Cookie。 这是我的中间件代码

import { NextResponse } from "next/server";

export async function middleware(req) {
    let token = req.cookies["refreshToken"];
    console.log(token);

    const { origin } = req.nextUrl

    const url = req.url

    if (url.includes('/profile') && !token) {
        return NextResponse.redirect(`${origin}/`)
    }

    if (token && url.includes('/profile')) {
        return NextResponse.next()
    }

}

有任何建议吗?还是它不能跨站点工作?但我可以存储 cookie,请记住这一点。

cookies next.js middleware vercel httpcookie
2个回答
0
投票

可能是跨站请求问题。如果您的后端托管在不同的域上,并且您将 SameSite 属性设置为 lax 或 strict 的 cookie,则您的前端代码将无法访问它(请参阅 MDN)。


0
投票

如果前端和后端在不同域,则在express中设置httponly cookie时需要设置domain属性。

  res.cookie("token", issueToken, {
    // can only be accessed by server requests
    httpOnly: true,
    // Make the cookie available on all subdomains of example.com
    ***domain: ".example.com",***
    // path = where the cookie is valid
    path: "/",
    // secure = only send cookie over https
    secure: true,
    // sameSite = only send cookie if the request is coming from the same origin
    sameSite: "none", // "strict" | "lax" | "none" (secure must be true)
    // maxAge = how long the cookie is valid for in milliseconds
    maxAge: 7 * 24 * 3600000, // 7 days
  });
© www.soinside.com 2019 - 2024. All rights reserved.