Express.js / Express.js with Sessions and Cookies
Cookie Management
This tutorial will guide you through managing cookies in Express.js. We'll cover creating, reading, updating, and deleting cookies to maintain state between requests.
Section overview
4 resourcesExplores managing sessions and cookies in Express applications.
1. Introduction
In this tutorial, we aim to guide you through managing cookies in Express.js. Cookies are a critical part of maintaining state between server and client requests. By the end of this tutorial, you will be able to create, read, update, and delete cookies using Express.js.
Before beginning, you should have a basic understanding of JavaScript, Node.js, and Express.js.
2. Step-by-Step Guide
Express.js doesn't handle cookies by default, we need to use a middleware called cookie-parser.
First, install cookie-parser:
npm install cookie-parser
After installing cookie-parser, we can include it in our application:
const express = require('express');
const cookieParser = require('cookie-parser');
const app = express();
app.use(cookieParser());
Now we are ready to manage cookies.
Creating Cookies
You can create cookies using the response.cookie() function. This function accepts three parameters: cookie name, cookie value, and options object.
app.get('/set', (req, res) => {
res.cookie('cookieName', 'cookieValue', {expire: 360000 + Date.now()});
res.send('Cookie is set');
});
Reading Cookies
Cookies can be read from the request.cookies object.
app.get('/get', (req, res) => {
res.send(req.cookies);
});
Updating Cookies
Updating a cookie can be done by setting the cookie again with the new value.
app.get('/update', (req, res) => {
res.cookie('cookieName', 'newCookieValue', {expire: 360000 + Date.now()});
res.send('Cookie updated');
});
Deleting Cookies
You can delete cookies using the response.clearCookie() function.
app.get('/clear', (req, res) => {
res.clearCookie('cookieName');
res.send('Cookie cleared');
});
3. Code Examples
Here is a complete example demonstrating all the actions we can perform on cookies.
const express = require('express');
const cookieParser = require('cookie-parser');
const app = express();
app.use(cookieParser());
// Set a new cookie
app.get('/set', (req, res) => {
res.cookie('myCookie', 'express', {expire: 360000 + Date.now()});
res.send('Cookie has been set');
});
// Get all cookies
app.get('/get', (req, res) => {
res.send(req.cookies);
});
// Update a cookie
app.get('/update', (req, res) => {
res.cookie('myCookie', 'updatedExpress', {expire: 360000 + Date.now()});
res.send('Cookie has been updated');
});
// Clear a cookie
app.get('/clear', (req, res) => {
res.clearCookie('myCookie');
res.send('Cookie has been cleared');
});
app.listen(3000, () => console.log('Server is listening on port 3000'));
4. Summary
In this tutorial, we have covered how to manage cookies in Express.js. We learned how to create, read, update, and delete cookies using cookie-parser middleware.
To continue learning, you can explore more about cookie options like HttpOnly, Secure, Domain, Path, and SameSite.
Additional resources:
- Express.js Documentation
- MDN Web Docs on HTTP Cookies
5. Practice Exercises
- Create an Express.js server that sets a user's name in a cookie.
- Update the previous exercise to display a welcome message to the user using the value in the cookie.
- Create an Express.js server that sets a counter in a cookie. Every time a user visits the site, increment the counter.
Solutions and explanations will be provided upon request. You can explore more about cookies and their options for more practice.
Need Help Implementing This?
We build custom systems, plugins, and scalable infrastructure.
Related topics
Keep learning with adjacent tracks.
Popular tools
Helpful utilities for quick tasks.
Latest articles
Fresh insights from the CodiWiki team.
AI in Drug Discovery: Accelerating Medical Breakthroughs
In the rapidly evolving landscape of healthcare and pharmaceuticals, Artificial Intelligence (AI) in drug dis…
Read articleAI in Retail: Personalized Shopping and Inventory Management
In the rapidly evolving retail landscape, the integration of Artificial Intelligence (AI) is revolutionizing …
Read articleAI in Public Safety: Predictive Policing and Crime Prevention
In the realm of public safety, the integration of Artificial Intelligence (AI) stands as a beacon of innovati…
Read articleAI in Mental Health: Assisting with Therapy and Diagnostics
In the realm of mental health, the integration of Artificial Intelligence (AI) stands as a beacon of hope and…
Read articleAI in Legal Compliance: Ensuring Regulatory Adherence
In an era where technology continually reshapes the boundaries of industries, Artificial Intelligence (AI) in…
Read article