How to use a Cookie Library In Javascript
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.
// 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
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