How can I use JavaScript for session tracking?

Jorge Jordão

Well, the closest thing you have is cookies. You can store values in cookies, either only for the duration of the session or persistent up to a specified expiration date.

In the example, I use a cookie called "username" to store a user's name in his first visit and another one called "visits" to keep a count of his number of visits to the page so far. I used the cookie handling functions (getCookie(name) and setCookie(name,value[,expirationDate]) defined in Netscape´s JavaScript Guide.

    <SCRIPT LANGUAGE="JavaScript">
      // include getCookie and setCookie functions here
    <SCRIPT LANGUAGE="JavaScript">
      var username = getCookie("username");
      if (username != null) { // registered user
        document.writeln("Welcome back " + 
          username + ".");
        var visits = getCookie("visits");
        document.writeln(" You have been here " +
          visits + " time(s) before.");
      else {                  // new user
        var username = prompt("What is your name ?","");
        if (username != null) {
          document.writeln("Thank you. Please reload this page.");

I used session cookies (which cease to exist as soon as the browser session ends), but I could have specified a expiration date and in that case they would persist until then.

Keep in mind however that while in a Java Servlet session you can store any Java objects in the server space, cookies are stored in the client and have several limitations. They can only store text, and (according to Netscape's JavaScript Guide)

  • The maximum number of cookies in the cookie file is 300
  • There is a maximum of 4 Kbytes per cookie, for the sum of both the cookie's name and value
  • There can be no more than 20 cookies per server or domain