N
Nuxt2y 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 (!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
Nuxt - middleware cookie (maybe bug) - StackBlitz
Create a new Nuxt project, module, layer or start from a theme with our collection of starters.
2 Replies
tDaniel
tDaniel2y ago
Same problem here
Patrik.S
Patrik.SOP2y ago
Any suggestion please? On version 3.0.0 it worked. Maybe it is too fast now?

Did you find this page helpful?