Implementing Web Cookies: A Beginner's Guide
Cookies are an essential part of web development, allowing websites to store small pieces of data on a user's device in a browser during or between sessions. In this blog post, we'll explore how to implement cookies using both vanilla JavaScript and Django, as well as discuss some common pitfalls and considerations.
Getting Started with Cookies
First, we will need to know how to set and get cookies.
Vanilla JavaScript Example:
// Set a cookie
document.cookie = "username=John Doe; expires=Thu, 18 Apr 2025 12:00:00 UTC; path=/";
// Get a cookie
const cookieValue = document.cookie
.split('; ')
.find(row => row.startsWith('username='))
.split('=')[1];
console.log(cookieValue);
Here is a function that I use for getting a cookie's value in Javascript:
function getCookie(name) {
const cookieString = document.cookie;
const cookies = cookieString.split(';');
for (let cookie of cookies) {
const [cookieName, cookieValue] = cookie.split('=').map(c => c.trim());
if (cookieName === name) {
return cookieValue;
}
}
return '';
}
Django Example:
from django.http import HttpResponse
def set_cookie(request):
response = HttpResponse("Cookie set!")
response.set_cookie('username', 'John Doe', expires=3600, path='/')
return response
def get_cookie(request):
username = request.COOKIES.get('username')
return HttpResponse(f"Hello, {username}!")
Editing Cookies
While setting and retrieving cookies are essential functionalities, there are times when you might need to edit existing cookies. This can be useful for updating cookie values or adjusting expiration dates. Here's a handy JavaScript function that I use for both setting and editing cookies:
// Function to set a cookie
function setCookie(name, value, days) {
var expires = "";
if (days) {
var date = new Date();
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
expires = "; expires=" + date.toUTCString();
}
document.cookie = name + "=" + (value ? "true" : "false") + expires + "; path=/";
}
This function allows you to set a cookie by providing the cookie name, value, and optionally the number of days until it expires. It automatically handles the expiration date calculation based on the provided number of days.
Note: You might encounter issues with multiple cookies being added if you're not careful. Ensure that you're replacing or updating existing cookies when needed to avoid cluttering the browser with redundant cookies.
Ensuring Your Site Allows Cookies
Now that you know how to set and get cookies, you will need to make sure that your site actually allows cookies. For many frameworks, this means enabling specific settings. Let's look at an example for Django.
Django Settings:
In your Django settings file (settings.py), make sure you have the following configuration:
# Ensure cookies are only sent over HTTPS
SESSION_COOKIE_SECURE = True
# Allow cookies to persist beyond the session
SESSION_EXPIRE_AT_BROWSER_CLOSE = False
There are other configurations surrounding cookies as well, such as
# Ensure that the CSRF token cookie is only sent over HTTPS
CSRF_COOKIE_SECURE = True
# Determine when and how the cookie should be sent in cross-origin requests
SESSION_COOKIE_SAMESITE = 'None'
# Allow the CSRF token cookie to be sent in cross-origin requests
CSRF_COOKIE_SAMESITE = 'None'
Hosting Considerations
When hosting your Django application, ensure that your server configuration allows cookies. For example, if you're using a DigitalOcean droplet with Nginx like I am, you can use the following:
Nginx Configuration:
Ensure that your Nginx configuration (usually in /etc/nginx/sites-available) allows cookies by including the following in your server block:
location / {
...
proxy_set_header Cookie $http_cookie;
...
}
Troubleshooting Cookie Persistence
While I was incorporating cookies to my project for the first time, I ran into the issue of them disappearing whenever the window was refreshed or the window session was in some other way was abandoned. I found out that the reason for this was because my cookies were not persisting like I had expected them to. If you encounter similar issues with cookies not persisting, use your browser's inspector tool to debug. Here's how to find cookies in commonly used browsers:
Google Chrome:
-
- Right-click on the webpage and select "Inspect."
- Go to the "Application" tab.
- Expand the "Cookies" dropdown on the left sidebar.
Mozilla Firefox:
-
- Right-click on the webpage and select "Inspect Element."
- Go to the "Storage" tab.
- Expand the "Cookies" dropdown.
Conclusion
Implementing web cookies is essential for maintaining user sessions and personalizing user experiences. By understanding how to set and manage cookies using both vanilla JavaScript and Django, as well as ensuring proper site and server configurations, you can enhance the functionality and usability of your web applications. Remember to always consider security best practices and test thoroughly to ensure smooth cookie functionality across different environments.