Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why can't I clear cookies in express

cookies just keeps adding on and on when I register a new user.

userRoutes.js

const { registerUser, loginUser, registerVerify } = require("./userController");

const express=require('express')
const router=express.Router()

router
    .route('/register')
    .post(registerUser)

module.exports=router

userController.js

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

const User = require("./userModel");
const validator = require("validator");
const jwt=require('jsonwebtoken')


const sendToken = function (email) {
  let data = {
    expiresIn: process.env.JWT_EXPIRE_SHORT,
    email,
  };
  let token = jwt.sign(data, process.env.JWT_SECRET_KEY);

  return token;
};

exports.registerUser = async (req, res, next) => {
  try {
    const { userName, email, password, confirmPassword } = req.body;
    let user = [
      { userName, email, password, confirmPassword, createdAt: Date.now() },
    ];

    //passwords do not match error
    if (password !== confirmPassword) {
      throw "Password doesn't match Confirm Password.";
    }

    //email not valid error
    if (!validator.isEmail(email)) {
      throw "Email not valid.";
    }

    //user already logged in error
    if (await User.findOne({ email })) {
      throw "User already exists. Please login";
    }

    //create user
    await User.create(user);

    //assign token
    let token = sendToken(email);

    //clear cookie
    
    res.status(200).clearCookie('token').cookie(token, 'token', {maxAge: 360000}).json({
      message: "Please fill the required text send via email",
      token,
    });
  } catch (err) {
    // console.log(err)
    res.status(400).json({
      message: "Signup Not Successfull",
      err,
    });
  }
};

I’ve tried
1.router
.route(‘/register’,{ credentials: ‘same-origin’})
.post(registerUser)

2.router
.route(‘/register’,{ credentials: ‘include’})
.post(registerUser)

3.router
.route(‘/register’,{ withCredentials: true})
.post(registerUser)

>Solution :

Here is the correct way for creating a cookie:

res.cookie('token', token, {maxAge: 360000});

Note: You don’t need to clear and create a new one.
when you send a cookie with the same key it overrides itself.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading