In Express.js, We can work with cookies to store and retrieve information on the client side.
Cookies are small pieces of data sent from a server and stored on the client's browser.
They are commonly used for various purposes, such as session management, user preferences, and tracking.
Here's an overview of working with cookies in Express.js:
we can use the `cookie-parser` package in express, for handling cookies.
npm install cookie-parser
const cookieParser = require('cookie-parser'); const express = require("express"); const app = express(); // Middleware to add cookieParser in request and response object app.use(cookieParser()); app.get("/set-cookie", (req, res) => { // Set a simple cookie with a key-value pair res.cookie("username", "AliceCollin"); // Set a cookie with options (e.g., expiration time) res.cookie( "user", { name: "Alice", age: 23 }, { maxAge: 900000, httpOnly: true } ); res.send("Cookies have been set!"); });
const cookieParser = require('cookie-parser'); const express = require("express"); const app = express(); // Middleware to parse JSON and URL-encoded data app.use(express.json({ limit: "50mb" })); app.use(express.urlencoded({ extended: true, parameterLimit: 50000 })); app.use(cookieParser()); const PORT = process.env.PORT || 3000; app.get("/set-cookie", (req, res) => { // Set a simple cookie with a key-value pair res.cookie("username", "AliceCollin"); // Set a cookie with options (e.g., expiration time) res.cookie( "user", { name: "Alice", age: 23 }, { maxAge: 900000, httpOnly: true } ); res.send("Cookies have been set!"); }); // Listening on the 3000 port app.listen(PORT, () => { console.log(`Server is running on http://localhost:${PORT}`); });
To set a cookie, we can use the "res.cookie()" method in our "route handler" or "middleware".
the route '/set-cookie' sets two cookies. The first one is a simple key-value pair ('username', 'AliceCollin'), and the second one is an object with options.
// when you search for http://localhost:3000/set-cookie Output in browser ---> Cookies have been set!
const cookieParser = require('cookie-parser'); const express = require("express"); const app = express(); // Middleware to parse JSON and URL-encoded data app.use(express.json({ limit: "50mb" })); app.use(express.urlencoded({ extended: true, parameterLimit: 50000 })); app.use(cookieParser()); const PORT = process.env.PORT || 3000; app.get("/get-cookies", (req, res) => { const username = req.cookies.username; const user = req.cookies.user; res.send(`Username: ${username}, User: ${JSON.stringify(user)}`); }); // Listening on the 3000 port app.listen(PORT, () => { console.log(`Server is running on http://localhost:${PORT}`); });
To retrieve cookies, we can use the "req.cookies" object.
// when you search for http://localhost:3000/get-cookies Output in browser ---> Username: AliceCollin, User: {"name":"Alice","age":23}
res.cookie('user', 'AliceCollin', { maxAge: 900000, httpOnly: true });
app.get('/clear-cookie', (req, res) => { res.clearCookie('username'); res.send('Cookie has been cleared!'); });
When setting cookies, we can provide various options such as maxAge (expiration time), httpOnly (accessible only through HTTP), secure (only sent over HTTPS), etc.
To clear a cookie, we can set its expiration time to a past date.
In the '/clear-cookie' route, the "res.clearCookie()" method is used to clear the 'username' cookie.