How to Set Cookies Session per Visitor in JavaScript?

Managing session cookies in JavaScript is essential for web developers to maintain user state and preferences across multiple sessions. The document. cookie property provides a basic mechanism for cookie management, utilizing JavaScript libraries or frameworks can offer enhanced security and flexibility.

Table of Content

  • Using the document.cookie Property
  • Using a Cookie Library
  • Using a Express and cookie-parser

Using the document.cookie Property

The document.cookie property can directly interact with cookies. It’s a simple method for basic cookie management without external dependencies. Here, Cookies are stored in key-value pairs separated by semicolons. The “document. cookie” property allows us to set, retrieve, and delete these cookies.

Example: The example below shows how to set cookies session per visitor in JavaScript using the document.cookie Property.

HTML
<!DOCTYPE html>
<html>

<head>
    <title>Set cookies session</title>
</head>

<body>
    <h2>Welcome To GFG</h2>
    <p>
       Default code has been 
       loaded into the Editor
      </p>
    <script>
        function storeUserState(stateName, 
                                stateValue, expiryDays = 0) {
            // Create a date object set to the current time.
            
              const currentDate = new Date();
            if (expiryDays > 0) {
                currentDate.setTime(currentDate
                           .getTime() +
                    (expiryDays * 24 * 60 * 60 * 1000));
            }

            const expires = "expires=" + 
                               currentDate.toUTCString();

            //Build the cookie string with 
           //name, value, expiration, and path.
            const cookieString = 
                  `${stateName}=${stateValue};${expires};path=/`;

            // Set the cookie using document.cookie
            document.cookie = cookieString;
        }

        function retrieveUserState(stateName) {
            const name = stateName + "=";
            const decodedCookie = decodeURIComponent(document.cookie);
            const stateEntries = decodedCookie.split(';');
            for (let i = 0; i < stateEntries.length; i++) {
                let stateEntry = stateEntries[i];
                while (stateEntry.charAt(0) === ' ') {
                    stateEntry = stateEntry.substring(1);
                }
                if (stateEntry.indexOf(name) === 0) {
                    return stateEntry
                      .substring(name.length, stateEntry.length);
                }
            }
            return "";
        }

        storeUserState("userSession", "loggedIn", 1);
        const userState = retrieveUserState("userState");
        console.log("Session value:", userState);
    </script>

</body>

</html>

Output :

Output

Using a Cookie Library

In this approach, The “cookie” module is imported to facilitate cookie handling in the Node.js environment. Define the name and value for the cookie to be set. Create a Date object representing the current time plus 1 day (24 hours * 60 minutes * 60 seconds * 1000 milliseconds). Define options for the cookie, including its expiration time and setting it as HTTP-only for added security. Serialize the cookie using the cookie.serialize method, which returns a string representation of the cookie.

Run the command to install the cookie:

npm i cookie

Example: The example below shows how to set cookies session per visitor in JavaScript using the cookie library.

JavaScript
// The cookie module is imported
const cookie = require("cookie");
const cname = "myCookie";
const cvalue = "cookieValue";

// Create a Date object.
const expires = new Date(Date.now() + 24 * 60 * 60 * 1000);

// Define options
const options = { expires: expires, httpOnly: true };
const cookieString = cookie.serialize(cname, cvalue, options);
console.log(cookieString);

Command to run the code:

node cookies1.js

Output:

myCookie=cookieValue; Expires=Fri, 10 May 2024 01:08:04 GMT; HttpOnly

Using Express and cookie-parser

Utilize the cookie-parser middleware to set a session cookie named “myCookie” with the value “cookieValue”. It configures the cookie to expire in one day and to be accessible only via HTTP requests. Upon receiving a GET request to “/”, it sets the cookie and sends a response confirming the successful cookie setting. Finally, the Express application listens on port 3000.

Run the command to install dependencies:

npm i express cookie-parser

Example: The example below explains how to set cookies session per visitor in javascript using an Express and cookie-parser.

JavaScript
const express = require("express");
const cookieParser = require("cookie-parser");
const app = express();
app.use(cookieParser());

app.get("/", (req, res) => {
    res.cookie("myCookie", "cookieValue", {
        maxAge: 24 * 60 * 60 * 1000,
        httpOnly: true,
    });

    // A response is sent with the message.
    res.send("Cookie set successfully");
});

//The Express application listens on port 3000.
app.listen(3000, () => {
    console.log("Server is running on port 3000");
});

Command to run the code:

node cookies1.js

Output:

Output