What is Cookies in NodeJs?
Cookies are used to maintain user session data and stored on a client side.
In NodeJs, cookie-parser module is used for cookies.
File Name :
npm install express cookie-parser --save
How to set Cookies?
For cookies first, we need to import the module in our app.js file and use it like other middlewares.
File Name :
var cookieParser = require('cookie-parser');
const app = express();
app.use(cookieParser());
res.cookie(name_of_cookie, value_of_cookie);
Example
File Name : app.js
let express = require('express');
let cookieParser = require('cookie-parser');
//setup express app
let app = express()
app.use(cookieParser());
//basic route for homepage
app.get('/', (req, res)=>{
res.send('Request Response');
});
//JSON object to be added to cookie
let users = {
name : "Sana",
Age : "2"
}
//Route for adding cookie
app.get('/setuser', (req, res)=>{
res.cookie("userData", users);
res.send('Set user data in cookie');
});
//Iterate users data from cookie
app.get('/getuser', (req, res)=>{
//shows all the cookies
res.send(req.cookies);
});
//server listens to port 3000
app.listen(3000, (err)=>{
if(err)
throw err;
console.log('listening on port 3000');
});
Adding Cookie with expiration Time
You can add a cookie with some expiration time i.e. after that time cookies will be destroyed automatically.
File Name :
res.cookie(cookie_name, 'cookie_value', {expire: 300000 + Date.now()});
//It also expires after 360000 ms from the time it is set.
res.cookie(cookie_name, 'cookie_value', {maxAge: 360000});
Secure cookies
File Name :
We can add several attributes to make this cookie more secure.
HTTPonly ensures that a cookie is not accessible using the JavaScript code. This is the most crucial form of protection against cross-scripting attacks.
A secure attribute ensures that the browser will reject cookies unless the connection happens over HTTPS.
app.get('/setcookie', (req, res) => {
res.cookie(`Cookie_name`,`Cookie_Value`,{
maxAge: 5000,
// expires works the same as the maxAge
expires: new Date('01 12 2021'),
secure: true,
httpOnly: true,
sameSite: 'lax'
// sameSite = Strict
});
res.send('Cookie have been saved successfully');
});
For the local host testing the server which uses a non-HTTPS secure., you can set secure: false. However, always use true value when you want cookies to be created on an HTTPS.
Deleting a cookie
File Name :
app.get('/deletecookie', (req, res) => {
//show the saved cookies
res.clearCookie()
res.send('Cookie has been deleted successfully');
});
Example :-
File Name :
npm install express cookie-parser --save
File Name : app.js
const express = require('express');
const cookieParser = require('cookie-parser');
const app = express();
// APPLYING AS MIDDLEWARE
app.use(cookieParser());
app.get('/', (req, res) => {
let cookieVal = req.cookies.username;
let show;
if (cookieVal) {
show = `Hi ${cookieVal} <br><a href="/delete-cookie">Delete Cookie</a>`;
} else {
show = `<a href="/set-cookie">Set Cookie</a><br>
<a href="/delete-cookie">Delete Cookie</a><br>`;
}
res.send(show);
});
// SET COOKIE
app.get('/set-cookie', (req, res) => {
res.cookie('username', 'Webtutorials.ME', {
maxAge: 1000 * 60, // 1 min
httpOnly: true // http only, prevents JavaScript cookie access
});
// REDIRECT OT HOME
res.redirect('/');
});
// DELETE COOKIE
app.get('/delete-cookie', (req, res) => {
//DELETING username COOKIE
res.clearCookie('username');
// REDIRECT OT HOME
res.redirect('/');
});
app.listen(3000, () => console.log('Your app listening on port 3000'));
Previous
Next