When a user clicks a button, I create 4 cookies before sending him to the next page:
$('button').on('click', function() {
create_cookie('cookie1', 'value1', 30);
create_cookie('cookie2', 'value2', 30);
create_cookie('cookie3', 'value3', 30);
create_cookie('cookie4', 'value4', 30);
window.location = 'nextpage/';
});
with create_cookie:
function create_cookie(name, value, lifetime) {
var date = new Date();
date.setTime(date.getTime() + (lifetime * 24 * 60 * 60 * 1000));
var expires = "; expires=" + date.toGMTString();
document.cookie = name + "=" + value + expires + "; path=/";
}
My question: am I sure that, using this approach, the cookies are set before the redirect? Or can it be that in some rare cases the cookies aren't set on time and the redirect already kicks in, resulting in a page load without the proper cookies? Given that the users' browser is set to accept cookies, of course.
Never had any issues myself, but in my error logs, I see that sometimes (although it's rare), the cookie isn't set on the next page for some users. This could of course be because the user visits the redirect page directly, and I could redirect them if the cookie is not set properly, but I want to be sure that the approach above is solid to avoid that users click the button and instantly get redirected to an error page because the cookie wasn't set properly.
Thanks a lot in advance!