Check Cookie And Take Action Using JavaScript

If you are making a website where you implemented login/logout functionality then cookie tracking is an important thing to do. Using this we can check if a user is logged in or not. Even if you are working on a user action-based project then it's also important. In this article, I will show you that how you can check cookies and take action according to that state.

check cookies and take action using JavaScript

Main Theory

Cookie checking is not a big deal. We can do this using simple JavaScript code. To do that we need the document then the cookie of that and then we can find out any specific cookie. Once you get that cookie then you can write different codes for decision making like show users that they are not logged in.

JavaScript Code

Here is the code formate you can use to check a specific code:

if (document.cookie.indexOf("cookiename") < 0) {
    alert("Cookie not found!");
    //take action here

You can redirect a user to the login page if they are trying to visit the dashboard without login. To do that you have to check the user login cookie and then you can use statements to take actions. Here is a demo code below:

if (document.cookie.indexOf("userLogin") < 0) {
    alert("Cookie not found, redirecting you.");
    window.location = "login.html";

In this way, you can do different things using cookies. We have more content on JavaScript. Check them so you can find something useful for your next project. Learn much new information about programming and technology from this website.

Post a Comment (0)
Previous Post Next Post