In my sveltekit app I have a “add to order” button in a product page. When the user clicks on it there is a cookie set with the product code, then the user is sent to the order page.
On the order page there is a form where the user can change product, on submit it will refresh the cookie updating its value.
The problem is that when I set a cookie from the order page, it won’t be updated if I try to create a new order, it will be updated only if I change product in the order page or if I manually delete the cookie. I’ve set the same path but it looks like server side cookies have the priority.
+layout.svelte
function handleClickOrderButton() {
const currentProduct = $page.params.product_id;
document.cookie = `orderSelectedProduct=; Max-Age=0; path=/; SameSite=None; Secure`;
try {
if(currentProduct){
document.cookie = `orderSelectedProduct=${currentProduct}; Max-Age=604800; path=/; SameSite=None; Secure`;
}
} catch (error) {
console.log(error)
} finally {
goto(`/${$page.params.database_id}/new-order`);
}
}
Form action
export const actions = {
changeSelectedProduct: async ({cookies, url, locals, request}) => {
if (!locals.user) {
return redirect(302, `/login`);
} else {
const userId = locals.user.id;
const formData = await request.formData();
const selectedProduct = formData.get("product");
try {
cookies.set("orderSelectedProduct", selectedProduct, {
path: "/",
maxAge: 604800,
sameSite: "None",
secure: true,
});
} catch (error) {
console.log(error);
}
}
}
};