Next.js Discord

Discord Forum

How can i read a cookie value I set in the middleware in a server action?

Unanswered
Polar bear posted this in #help-forum
Open in Discord
Polar bearOP
I am setting a cookie "browsing_id" with a uuid v4. I set it in the middleware and I read it in a server action. It is working fine except for the first time the server action is called.
// middleware.ts
  let id = req.cookies.get("browsing_id")?.value;

  if (id == null) {
    id = v4();
    req.cookies.set({ name: "browsing_id", value: id });
  }

  res.cookies.set({ name: "browsing_id", value: id });



In my server action im just using cookes() from next/headers

On the first page load the cookies().get("browsing_id") returns undefined the subsequent reloads the cookies().get("browsing_id") returns the uuid v4 how can i make it work the first time.

11 Replies

Polar bearOP
hi i see i think what im doing is that im calling the server action in the page async function
so yeah my question should be reading cookies set in middleware from page.tsx
headers could work ill try it
soooo what are you trying to achieve again sorry?
Polar bearOP
im trying to set the cookie "browsing_id" in the middleware if it doesn't exist and then in my page files read that value to render approproate content. For example in one page file i use that id to check if there are any cart items for that browsing id and render them. The problem is that sometimes it appears as null and my helper function that gets the cart items fails. This happens on the first load when the cookie is set first. For example if the first page i go to is the cart my helper function can't find the id assigned.
or if i were to just render the browsing id it would happen too the first load shows null id although it is set in the middleware
Polar bearOP
//middleware
  if (request.cookies.get("browsing_id") == null) {
    let id = v4();
    response.cookies.set("browsing_id", id);
    response.headers.set("browsing_id", id);
  }


// helper function to get the browsing id
const getBrowsingId= () => {
  return (
    cookies().get("browsing_id")?.value || headers().get("browsing_id")
  );
};


This ended up working (covering the case of the first load too)
nice