How to use Express and cookie-parser In Javascript

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



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

Similar Reads

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....

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....

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....