尝试使用next.js在getServerSideProps中设置cookie

dxpyg8gm  于 2023-03-22  发布在  其他
关注(0)|答案(1)|浏览(205)

我试图在getServerSideProps中设置cookie,我可以使用`req.headers.cookie读取它,但当试图设置它时,它不起作用,我还尝试使用其他库,如cookies-next,但它没有持久:
下面是设置Cookie的中间件,我可以在getServerSideProps上读取:

export function middleware(request: NextRequest) {

const response = NextResponse.next()

response.cookies.set({
    name: 'myCookieName',
    value: 'some-value',
    httpOnly: true,
})


return response

}
我的getServerSideProps除了使用req.headers.cookie阅读cookie并尝试设置它的日志之外什么都没有。感谢您花时间阅读本文

gblwokeq

gblwokeq1#

您可以使用npm cookie package

import { serialize } from "cookie";
import { GetServerSideProps } from "next";

const YourPage = () => {
  return <div>YourPage</div>;
};
export default YourPage;

export const getServerSideProps: GetServerSideProps = async ({ res }) => {
  const cookie = serialize("cookieName", "cookieValue", {
    httpOnly: true,
    maxAge: 60 * 60 * 24 * 7 // 1 week
  });

  console.log("cookie", cookie);
  console.log("res object", res);

  res.setHeader("Set-Cookie", cookie);
  return {
    props: {},
  };
};

相关问题