How To Set – Get Cookies With Express And MongoDB

How To Set & Get Cookies In Node Js ( Express ) With MongoDB

Hey, Developers! In This Blog Post, We Will Walk You Through How To Set & Get Cookies With Express And MongoDB. Cookies Play An Important Role In Storing Data About User Sessions And Preferences On The Client Side.

Setting & Getting Cookies Are Very Important When It Comes To Managing User Sessions & User Data. This Also Helps To Make Our Application More Secure As It Helps To Access Our Application With The Authenticated User.

We will explore the step-by-step process of setting cookies to store user data securely and retrieve them when needed. We Will Use A Cookie Parser & Other Useful Packages To Do This, Setting & Getting Cookies Might Be Easy But It Requires Good Implementation To Ensure The Security Of The Web Application.

Also Read: JWT Authentication In Express With MongoDB

At The End Of This Post, You Will Have A Clear Understanding Of How To Use Cookies With Express And MongoDB. So Let’s Get Started!

How We Are Going To Set & Get Cookies? At first, We Will Create A User By Taking The Name, Email & Password, And This User In The database.

Then We Will Create An Endpoint For User Login In Which We Will Take A Unique ID From The Database Create A Token With JWT Token & Set This Token In The Form Of A Cookie. That Is What Setting Cookie Means.

Now We Will Create One Middleware For Authentication In Which We Will Request A Cookie To The User That We Have Created At The Time Of Login & Verify The Cookie With JWT & If It Is Verified Successfully We Will Allow The User To Navigate To The Particular Page. This Is What Getting Cookies From The Front End For Authentication Means.

NPM Packages For Getting & Setting Cookies

Here Is A List Of NPM Packages That Are Used To Set & Get Cookies With Express And MongoDB:

  1. Express: Minimal Framework Made On The Top Of Node Js.
  2. Mongoose: Connect & Communicate To The Database From Express Backend.
  3. Cookie Parser: Middleware To Parse The Cookies Coming Or Attacked To The Request Body Coming From Frontend.
  4. Json Parser: Parse The Data In The Json Formate Coming From the Form From Frontend.

How To Set Cookies In Express ( Writing Cookies )

Now, let’s start setting cookies in Express. We Will Keep This Project Tightly Stuck To Our Topic & Will Create the Necessary Files.

Basic Folder Structure:

  1. Create One Folder On The Desktop Called “Set & Get Cookies”.
  2. Create App.js File: Starting Point For Our Express Application.
  3. Create User.js File: Helps To Create User Schema For Creating User Document In the Database.

After Creating All These Files Open The Terminal And Initialize Your Folder For Our Project Using The ‘npm init’ Command.

Then Install Required Packages Shown Above. After Installing All The Required Packages. After Installing All The Packages Your Package.json File Will Look Something Like This:

Package.json File For Setting &  Getting Cookies With Express And MongoDB

Creating App.js File

Now We Will Create A Basic App.js File To Set & Get Cookies. In The App.js Files, We Will Require A Body Parser, Express, and Mongoose.

Then We Will Create An Express Application & Assign It To The App Variable. Then Define The Port & Create Post Routes For Registration & Sign.

We Will Also Create One Get Route That Can Be Only Accessed By The Authenticated User. At Last, We Will Listen To Our App To Our Defined Port As Shown In The Following Code:

const bodyParser = require("body-parser");
const express  = require("express");
const mongoose = require("mongoose");
const app = express();
const Port = 8080;

//use
app.use(express.json());
app.use(bodyParser.urlencoded({extended: true}));

app.get("/registration", (req,res)=>{
  
})
app.get("/signin", (req,res)=>{

})
app.listen(Port, ()=>{
    console.log("Server Started At: " + Port)
})

Creating User Schema

To Create A User Schema We Will Go To Schema.js File. We Will Import the Mongoose package and create a new Mongoose schema with the help of “new mongoose.Schema({ }) & assign it to the UserSchema Variable.

We have to define what we have to store & in which format we have to store the values in UserSchema. We will store:

  1. The name of the user of the type string & name is required.
  2. The Email Of The User Of The Type String & Email Is Required & Should Be Unique.
  3. The Password Of The User Which Is Of Type String & Required

At the last, we have to store this schema in the model called Users. As Shown In Following Code.

const mongoose = require("mongoose");

const UserSchema = new mongoose.Schema({
    name:{
        type: String,
        required: true,
    },
    email:{
        type: String,
        required: true,
        unique: true,
    },
    password:{
        type: String,
        required: true,
    }
})

const schema = mongoose.model("Users", UserSchema);
module.exports = schema;

All the models are located in the database. So At First, We Have To Connect To The Database As Follows:

mongoose.connect('mongodb://localhost:27017/your_database_name', {
  useNewUrlParser: true,
  useUnifiedTopology: true,
  useCreateIndex: true, // Needed to use 'unique' in schema
})
MongoDB Database Name & Model Names

Create A User Registration Route

To Register An User In The Database We Have To Create an Async Route. We Will Request The Name, Email & Password From The Body Of the Request with req.body.

We Will Also Import The User Schema In Our App.js File. As Shown In the following Code:

const mongoose = require("mongoose");
const user_schema = require("./schema");

This Allow Us To Perform CRUD Operations in the database. Now user. schema has various methods, we will use the create method to create & save the user in the database. In the create method we will pass the name, email & password coming from the request.

After the user saves we will send the status of 201 & message “User Created Successfully”

app.post("/registration", async (req,res)=>{
    const {name, email, password} = req.body
     await user_schema.create({name, email, password})
     res.status(201).json({message: "User Created Successfully"});
})

Create A User Signin Route

At The Time Of signing We Need To Set (Send) a Cookie To The Client In Order To Authentication. At first, we will create an /signin post route with the async controller to handle the request.

We Will request an email & password from the client & if any of the fields is missing we will send 404 error. Now if the user enters the right credentials we will find the user with an email with findone() method.

If the User is not present in the database we will send “You Have To Register First To SignIn” message. Now if we find the user we will check for the password & if It is correct we will send a cookie as a response with the token & key as shown in the following code:

app.post("/signin", async (req,res)=>{
    const {email, password} = req.body
    if(!email || !password){
        res.status(404).status({message: "Invalid Credentials"});
    }
    let find_user = await user_schema.findOne({email})
    if(!find_user){
        res.status(404).json({message: "You Have To Register First To SignIn"})
    }
    if(password !== find_user.password){
        res.status(404).json({message: "Invalid Credentials"});
    }
    if(password === find_user.password){
        res.cookie('token', "hi");
        res.status(201).json({message: "Login Successful"})
    }
})

That Is How We Can Set Cookies From Backend To Frontend. This is just a basic method to make it more secure we will encrypt the cookie with a Package name called JSON Web Token.

To encrypt the cookie we will include a JSON web token in our project and create JSW secret code as shown in the following code:

const jwt = require("jsonwebtoken");
const jwtsecrate = 'javascriptsmagic';

Now let’s encrypt the cookie with JWT sign function. In the JWT sign method, we have to pass id & email, JWT secret key & other parameters like expires as shown in the following code. This is how we set cookies with JWT encryption.

 if(password === find_user.password){
        let token = jwt.sign({id: find_user._id, email: find_user.email}, jwtsecrate, {expiresIn: '1h'});
        res.cookie('token', token);
        res.status(201).json({message: "Login Successful"})
}

Now Let’s test the sign-in route & check if the cookie is present or not. We will use Thunder Client For This. If we enter the correct email & password & hit the send button the backend will respond success message & cookie with an encrypted token as shown in the following Image.

Package.Json File After NPM INIT 3 1

How To Get Cookies In Express ( Reading Cookies )

Getting Cookies Simply Means Requesting Cookies From Client That We Have Sent While Login. We Request ( Get ) Cookies to authenticate the user this gives the ability to show specific pages to particular users.

So let’s create an authentication middleware that requests or gets cookies from the user & verifies if the cookie is valid or not. It is valid we will allow to access /dashboard route to the user.

At first, we have to create an async controller & assign it to the authentication variable. This function requests tokens from cookies that we have sent while logging.

If there is no token available then we will send a message of “session Expired”. If the token is present we will verify it with the verification method provided by JWT. To verify the token we have to match it with the jwtsecrate key that we have created.

Now if the token is verified we will call the next() function as shown in the following code:

const authentication = async (req, res, next) => {
  let get_token = req.cookies.token;
  if (!get_token) {
    return res.status(404).json({ message: "Session Expired" });
  }

  try {
    let verify = await jwt.verify(get_token, jwtsecrate);
    req.user = verify; // Attach the decoded token payload to the request object
    next(); // Pass control to the next middleware or route handler
  } catch (error) {
    return res.status(401).json({ message: "Something Went Wrong, Please Login Again" });
  }
};

Now we have to add this middleware before the controller function of the endpoint as shown in the following code.

app.get("/dashboard", authentication,  (req,res)=>{
    res.status(201).json({message : "Welcome To DashBoard"})
})

Now Let’s Check If It Is Working or Not:

Step1: Login To Check Cookies:

Login With Credentials to check cookies

After entering Proper Credentials we have a message of Login Successful.

Step2: Access The DashBoard Route

Accessing Dashboard Route After Login

If We try To Access The Dashboard Route We Can Access It As Shown In The Above Image.

Step3: Acees By Removing Cookies

If We Remove The Cookie We Are Not Able To Access The DashBoard As Shown In The Above Video.

Conclusion

This is how we set & get cookies in Express with mongoDb. Here Is the Complete Code:

App.js File:

//App

const bodyParser = require("body-parser");
const express  = require("express");
const mongoose = require("mongoose");
const jwt = require("jsonwebtoken");
const jwtsecrate = 'javascriptsmagic';
const cookieparser = require("cookie-parser");
const user_schema = require("./schema");
const app = express();
const Port = 8080;

//connection to database

mongoose.connect("mongodb://localhost:27017/WebDevPro").then(()=>{
    console.log("DataBase Is Connected Successfuly");
});

//use
app.use(express.json());
app.use(bodyParser.urlencoded({extended: true}));
app.use(cookieparser());


//authentication middleware

const authentication = async (req, res, next) => {
  let get_token = req.cookies.token;
  if (!get_token) {
    return res.status(404).json({ message: "Session Expired" });
  }

  try {
    let verify = await jwt.verify(get_token, jwtsecrate);
    req.user = verify; // Attach the decoded token payload to the request object
    next(); // Pass control to the next middleware or route handler
  } catch (error) {
    return res.status(404).json({ message: "Something Went Wrong, Please Login Again" });
  }
};

app.get("/dashboard", authentication,  (req,res)=>{
    res.status(201).json({message : "Welcome To DashBoard"})
})



app.post("/registration", async (req,res)=>{
    const {name, email, password} = req.body
     await user_schema.create({name, email, password})
     res.status(201).json({message: "User Created Successfully"});
})


app.post("/signin", async (req,res)=>{
    const {email, password} = req.body
    if(!email || !password){
        res.status(404).status({message: "Invalid Credentials"});
    }
    let find_user = await user_schema.findOne({email})
    if(!find_user){
        res.status(404).json({message: "You Have To Register First To SignIn"})
    }
    if(password !== find_user.password){
        res.status(404).json({message: "Invalid Credentials"});
    }
    if(password === find_user.password){
        let token = jwt.sign({id: find_user._id, email: find_user.email}, jwtsecrate, {expiresIn: '1h'});
        res.cookie('token', token);
        res.status(201).json({message: "Login Successful"})
    }
})

app.listen(Port, ()=>{
    console.log("Server Started At: " + Port)
})

UserSchema:

const mongoose = require("mongoose");

const UserSchema = new mongoose.Schema({
    name:{
        type: String,
        required: true,
    },
    email:{
        type: String,
        required: true,
        unique: true,
    },
    password:{
        type: String,
        required: true,
    }
})

const user_schema = mongoose.model("Users", UserSchema);
module.exports = user_schema;

Last Updated: August 9, 2024

By JSM Hemant

About Author

Hello, Myself Hemant. I Am Web Developer & Likes To Create Awesome Projects By Using MERN, Java, Python, C++. In This Website You Will Get Cool Projects Made With Above Technologies With Full Source Code. You Can Also Follow This Website On Author Social Media:

Leave a Reply

Your email address will not be published. Required fields are marked *

Categories

Recent Posts