NodeJs Tutorials
- NodeJs
- Install NodeJs
- Why use NodeJs
- NodeJs Process Model
- create First Application
- Run NodeJs Application
- Node.js Console
- Node.Js Modules
- URL Modules
- node.js Callback
- Node.js Events
- Upload Files
- Upload single & Multiple Files
- NodeJs File System
- NodeJs Email
- Debugging NodeJs
- .ENV
- NodeJs Mysql
- Helpers
- encription and decription in nodeJs
- Query string
- Date & Time
- Express Js
- Template Engine with Express
- MVC Pattern in Node.Js
- list of NPM Module
- Middleware
- Body Parser
- Render
- Nodemon module
- Morgan module
- Flash Message in ExpressJs
- Session
- Session store in database
- Cookies
- Helmet
- Multer
- Router: How To Use Routing In Node.Js
- App.Js
- express.json() and express.urlencoded()
- REST APIs in NodeJs
- Gloabal Objects
- Submit Form Data
- How to get Post Data in Node.js
- How to Get URL Parameters in Node.js
- How to create Node Project
- How to Insert Form Data Into the MySql Table Using Node.js
- How to fetch Data from MySQL database table using Node.js
- CRUD Example
- Await and Async
- Promises
- Login Example
- Password Encription
- How to validate Form (Form Validation) in Node.Js?
- Registration & Login form usingn Node.Js & MySql?
- Forgot & Reset Password
- File Upload in Node.Js with ExpressJs
- Resize Image Before Upload using Multer Sharp
- Upload multiple file using node.js with multer module
- Upload file using node.js with multer module
- Client IP Address
- REST API Downloading File in NodeJs
- Export and Download CSV From MySQL Database
- CRUD REST API
- CRUD REST API Example 2
- Enable HTTPS using Node
- How to send EMAIL using NodeJs?
- Dynamic dependent dropdown using NodeJs?
- Autocomplete Search
- Get and Send Data From Ajax Request
- Get and Post Data using Ajax
- Passport Authentication
- Node Js Data type
- Node Js Error
- Node Js Array Function
- Node Js String Function
- Puppeter Module
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'));