In this tutorial, you will learn how to create/set, get, and delete cookies in node js + express js applications.
Create, Get & Delete Cookies with Node Express JS Server
Here are steps:
Step 1 – Create Node Express js App
Run the following command on cmd to create node js app:
mkdir my-app cd my-app npm init -y
Step 2 – Install cookie-parser node module
Run the following command on the cmd to install express and cookie parser modules:
npm install express cookie-parser --save
Step 3 – Create Cookie Route
Create a cookie route and use res.cookie([cookie name], [options object])
which allows you to set cookies:
// 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('/'); });
Step 4 – Get Cookie Route
Get cookie route in node js + express app:
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); });
Step 5 – Delete Cookie Route
Create a cookie deletion route using res.ClearCookie('name')
that allows deleting cookies:
// DELETE COOKIE app.get('/delete-cookie', (req, res) => { //DELETING username COOKIE res.clearCookie('username'); // REDIRECT OT HOME res.redirect('/'); });
Step 6 – Create App.js File
Go to your node js app directory and create app.js file, and all the routes in it:
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'));
Step 7 – Test This Application
You can use the following command to start node js app server:
//run the below command
npm start
Open your browser and hit
http://127.0.0.1:3000/