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