0

I am trying to set the cookie in the getServerSideProps, i am able to read it using `req.headers.cookie but when trying to set it, it doesnt work i tried also using other libraries like cookies-next but it did not persist:

here is the middleware which sets a Cookie and that i am able to read on getServerSideProps:

export function middleware(request: NextRequest) {

const response = NextResponse.next()

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



return response

}

my getServerSideProps has nothing except for logs reading the cookie using req.headers.cookie and attempts to set it. Thanks for taking the time to read this

Yilmaz
  • 35,338
  • 10
  • 157
  • 202
Camille Basbous
  • 299
  • 5
  • 11
  • 34

1 Answers1

0

you can use 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: {},
  };
};
Yilmaz
  • 35,338
  • 10
  • 157
  • 202
  • Hi @Yilmaz, thanks for the suggestion but when refreshing and removing the set after setting once the data does not persist only the one in the middleware is shown – Camille Basbous Mar 18 '23 at 16:55
  • you could add `maxAge` property. you can check the npm docs for more oprions or ts suggestion – Yilmaz Mar 18 '23 at 17:00
  • tried using maxAge as suggested but still did not persist – Camille Basbous Mar 18 '23 at 17:09
  • how do you know that it is not persisted. open chrome tools, click on "Applications" tab, on the left menu, under "Storage" category, click on cookies. you see the url for your app – Yilmaz Mar 18 '23 at 17:11
  • So i tried with the code you gave me to set it and when doing that i logged it and it showed but then i just removed the set to see if it will log after refresh, it doesn't. So im removing this part for the second log const cookie = serialize("cookieName", "cookieValue", { httpOnly: true, maxAge: 60 * 60 * 24 * 7 // 1 week }); res.setHeader("Set-Cookie", cookie); and im looking that its stored on server side not browser – Camille Basbous Mar 18 '23 at 17:56
  • @CamilleBasbous i removed `setHeader`, restart the app and cookie is still there – Yilmaz Mar 18 '23 at 18:39