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.
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.
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');
});
Cookies can be read from the request.cookies
object.
app.get('/get', (req, res) => {
res.send(req.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');
});
You can delete cookies using the response.clearCookie()
function.
app.get('/clear', (req, res) => {
res.clearCookie('cookieName');
res.send('Cookie cleared');
});
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'));
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
Solutions and explanations will be provided upon request. You can explore more about cookies and their options for more practice.