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

12 messages · Page 1 of 1 (latest)

uncut marsh
#

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.

novel rampartBOT
#

🔎 This post has been indexed in our web forum and will be seen by search engines so other users can find it outside Discord

🕵️ Your user profile is private by default and won't be visible to users outside Discord, if you want to be visible in the web forum you can add the "Public Profile" role in id:customize

✅ You can mark a message as the answer for your post with Right click -> Apps -> Mark Solution
(if you don't see the option, try refreshing Discord with Ctrl + R)

frail pulsar
uncut marsh
#

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

frail pulsar
#

soooo what are you trying to achieve again sorry?

uncut marsh
#

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

frail pulsar
#

thats why try set the header first then read the headers at server action

uncut marsh
#

//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)