NuxtN
Nuxt3y ago
Patrik.S

Undefined cookie inside middleware

https://stackblitz.com/edit/nuxt-starter-zctfjj?file=middleware/createContractId.ts

Hey, I am trying to resolve the cookie inside middleware.

When I set cookie and navigateTo I get undefined cookie after refresh page the cookie is known.

I work with something like this:

if (!contractId && process.server) {
    const contract: { id: string } = await $fetch('/api/get-contract-id');
    // when i got contractId a set it up too cookie
    setCookie({ contractId: contract.id });

    // after setup cookie i redirect to page vie name
    return navigateTo({
      name: `online-contractId-first-page`,
      query: {
        ...from.query,
      },
      params: {
        contractId: contract.id,
      },
    });
  }

  // after navigate the cookie is undefined, and when i hit f5 its working
  console.log(cookie);
  if (!cookie) {
    throw createError({
      message: 'Cookie not exist',
      fatal: true,
    });
  }


if I try setTimout the navigateTo approx. 300ms then it works

any tip what can i do?
StackBlitz
Create a new Nuxt project, module, layer or start from a theme with our collection of starters.
Was this page helpful?