Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to set cookie value with AJAX request in JavaScript?
When making AJAX requests in JavaScript, you often need to send cookies to the server for authentication or session management. Fortunately, modern browsers automatically include cookies in AJAX requests to the same domain, but you need to set them properly first.
How Cookies Work with AJAX
AJAX requests automatically send all relevant cookies to the server without additional configuration. The key is setting the cookie correctly using JavaScript's document.cookie property before making your AJAX call.
Setting a Basic Cookie
Here's how to set a simple cookie that will be sent with AJAX requests:
<script>
// Set a basic cookie
const token = 'some_auth_token_12345';
document.cookie = `token=${token}`;
// Verify the cookie was set
console.log('Current cookies:', document.cookie);
// Make an AJAX request - cookie will be sent automatically
fetch('/api/data')
.then(response => response.json())
.then(data => console.log('Response:', data))
.catch(error => console.error('Error:', error));
</script>
Setting Cookie with Expiration Date
To set a cookie that expires at a specific time, include the expires attribute:
<script>
// Set cookie with expiration date
const token = 'auth_token_67890';
const expiry = new Date('2025-12-31T23:59:59Z').toUTCString();
document.cookie = `token=${token}; expires=${expiry}; path=/`;
console.log('Cookie set with expiry:', expiry);
console.log('All cookies:', document.cookie);
// AJAX request will include this cookie
const xhr = new XMLHttpRequest();
xhr.open('GET', '/api/user-profile');
xhr.onload = function() {
if (xhr.status === 200) {
console.log('Profile data:', xhr.responseText);
}
};
xhr.send(); // Cookie sent automatically
</script>
Complete Example with Cookie Options
Here's a comprehensive example showing various cookie attributes:
<script>
function setCookieForAjax(name, value, days) {
let expires = '';
if (days) {
const date = new Date();
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
expires = '; expires=' + date.toUTCString();
}
// Set cookie with security options
document.cookie = `${name}=${value}${expires}; path=/; SameSite=Strict`;
console.log(`Cookie '${name}' set successfully`);
}
// Set authentication cookie
setCookieForAjax('sessionId', 'abc123def456', 7); // Expires in 7 days
// Function to make AJAX request
function makeAuthenticatedRequest() {
fetch('/api/protected-data', {
method: 'GET',
credentials: 'same-origin' // Ensures cookies are included
})
.then(response => {
if (response.ok) {
return response.json();
}
throw new Error('Request failed');
})
.then(data => {
console.log('Protected data received:', data);
})
.catch(error => {
console.error('Error fetching protected data:', error);
});
}
// Test the setup
console.log('Current cookies before request:', document.cookie);
makeAuthenticatedRequest();
</script>
Key Points
- Cookies are automatically sent with AJAX requests to the same domain
- Use
document.cookieto set cookies before making requests - Include
credentials: 'same-origin'in fetch() for explicit cookie handling - Set appropriate
pathandSameSiteattributes for security - For cross-origin requests, use
credentials: 'include'and proper CORS setup
Conclusion
Setting cookies for AJAX requests is straightforward using document.cookie. Once set, browsers automatically include these cookies in subsequent AJAX calls to the same domain, enabling seamless authentication and session management.
