This tutorial aims to equip you with the best practices for handling cookies in Express.js, a popular web application framework for Node.js. We will go over the process of setting, securing, and optimizing cookies.
By the end of this tutorial, you'll understand how to:
This tutorial assumes that you have a basic understanding of JavaScript and Node.js, and that you're familiar with Express.js.
Cookies are small pieces of data stored on the client's browser. They are used to remember stateful information for the stateless HTTP protocol.
In Express.js, we use the cookie-parser
middleware to work with cookies.
const express = require('express');
const cookieParser = require('cookie-parser');
const app = express();
app.use(cookieParser());
To set a cookie, we use the response.cookie()
method.
app.get('/', (req, res) => {
res.cookie('name', 'express').send('cookie set'); // Sets name=express cookie.
});
To read cookies, you simply use request.cookies
.
app.get('/', (req, res) => {
console.log('Cookies: ', req.cookies);
});
Here, we'll set a cookie with the httpOnly
and secure
options. httpOnly
prevents the cookie from being accessed through client-side scripts, while secure
ensures the cookie is sent over HTTPS.
app.get('/', (req, res) => {
res.cookie('name', 'express', { secure: true, httpOnly: true }).send('cookie set');
});
To delete a cookie, you use the response.clearCookie()
method.
app.get('/clear_cookie', (req, res) => {
res.clearCookie('name');
res.send('cookie name cleared');
});
In this tutorial, you have learned how to set, secure, read, and delete cookies in Express.js. You also learned how to use the cookie-parser
middleware.
Next, you could learn about sessions in Express.js, which is a related subject. For more information, consult the Express.js documentation and this article on the cookie-parser
package.
userID
with a value of 1234
and then read it.Solution:
js
app.get('/', (req, res) => {
res.cookie('userID', '1234').send('cookie set');
console.log('Cookies: ', req.cookies);
});
sessionID
with a value of abcd
, make it secure and httpOnly. Afterwards, try to delete it.Solution:
```js
app.get('/', (req, res) => {
res.cookie('sessionID', 'abcd', { secure: true, httpOnly: true }).send('cookie set');
});
app.get('/clear_cookie', (req, res) => {
res.clearCookie('sessionID');
res.send('cookie sessionID cleared');
});
```
Solution:
js
app.get('/', (req, res) => {
res.cookie('name', 'express');
res.cookie('userID', '1234');
res.cookie('sessionID', 'abcd');
res.send('cookies set');
console.log('Cookies: ', req.cookies);
});
Remember to keep practicing and exploring more functionalities of cookies in Express.js!