How to set cookie value with AJAX request in JavaScript?


We are required to set cookies with AJAX requests or in such a way that any AJAX request sends those cookies to the server.

One thing to note here is that every AJAX request made to any remote server automatically sends all our cookies to that very server without us having to do anything. Therefore, with this thing clear, we just have to set a specific key to our document object using JavaScript and whenever we make a network call, that cookie will automatically be sent to the server which we are making the call to.

The code for setting the cookie will be −

const token = 'some 323 very 535 random 5445 value';
document.cookie = `token=${token}`;

If we want a cookie that expires at a certain time in future, we can create that with the following code −

const token = 'some 323 very 535 random 5445 value';
const expiry = 'Wed, 4 Feb 2021 12:00:00 UTC';
document.cookie = `token=${token} expires=${expiry}`;

This way, when we make any network request the ‘token’ cookie will automatically be sent to the server.

Updated on: 22-Feb-2021

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements