Skip to content
Advertisement

How to delete a cookie in Reactjs

I am developing a web app with react front-end and node baack-end

I want to delete the cookie being stored so that I can successfully be able to logout the user. I have tried using the js-cookie library and react-cookie library but it does not work.

nav_component:

import React from "react";
import { Link, useHistory } from "react-router-dom";
import { useSelector } from "react-redux";
import { NavDropdown } from "react-bootstrap";
import Cookies from "js-cookie";

function Nav() {
  const user = useSelector((state) => state.user);
  const { name, id, loginId } = user;
  const history = useHistory();

  function logout() {
    Cookies.remove("userId", { path: "/", domain: "localhost" });
    localStorage.clear();
    history.push("/login");
  }

  return (
    <nav className="navbar navbar-expand navbar-light fixed-top">
      <ul class="nav">
        <li class="nav-item">
          <Link to={"/"} class="nav-link active" aria-current="page">
            Home
          </Link>
        </li>
        <li class="nav-item">
          <Link to={"/register"} class="nav-link">
            Register
          </Link>
        </li>
        <li class="nav-item">
          <Link to={"/login"} class="nav-link">
            Login
          </Link>
        </li>
        <li class="nav-item">
          <Link
            to={"/admin"}
            class="nav-link"
            tabindex="-1"
            aria-disabled="true"
          >
            Admin
          </Link>
        </li>
      </ul>
      {name ? (
        <ul class="username">
          <li>
            <NavDropdown title={name}>
              <NavDropdown.Item>
                {id}: {loginId}
              </NavDropdown.Item>
              <NavDropdown.Item onClick={logout}>Logout</NavDropdown.Item>
            </NavDropdown>
          </li>
        </ul>
      ) : null}
    </nav>
  );
}

export default Nav;

How I set the cookie in the backend:

app.use(cookieParser());
app.use(
  express.urlencoded({
    extended: true,
  })
);

app.use(
  session({
    key: "userId",
    secret: "subscribe",
    resave: false,
    saveUninitialized: false,
    cookies: {
      expires: 60 * 60 * 8,
    },
  })
);
app.get("/login", (req, res) => {
  if (req.session.user) {
    res.send({ loggedIn: true, user: req.session.user });
  } else {
    res.send({ loggedIn: false });
  }
});

app.post("/login", (req, res) => {
  const LoginID = req.body.LoginID;
  const Password = req.body.Password;
  db.query(
    "SELECT * FROM usermst WHERE LoginID = ? AND password = ?",
    [LoginID, Password],
    (err, result) => {
      if (err) {
        res.send({ err: err });
      }

      if (result.length > 0) {
        const userid = result[0].UserID;
        const token = jwt.sign({ userid }, "jwtSecret", {
          expiresIn: 60 * 60 * 24,
        });
        req.session.user = result;

        res.json({ auth: true, token: token, result: result });
      } else {
        res.send({ message: "Wrong LoginID/Password combination" });
      }
    }
  );
});

It should be noted that in my backend there is some code related to JWT tokens but I have not yet implemented that in my front-end. The only thing that I have implemented is the cookie and session.

Advertisement

Answer

In my backend I added this code for logging out to which I made an axios reques from the frontend:

  res.clearCookie("userId", { path: "/" });
  res
    .status(200)
    .json({ success: true, message: "User logged out successfully" });
};

app.get("/logout", logout, (req, res) => {
  res.send("You have been logged out successfully");
});

Whereby “userId” id the name of the cookie

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement