Cookies In JS

???? Enhance Your Website with Cookies - A Simple Guide!

Hey LinkedIn community! ???? Today, I want to share a quick and helpful code snippet for managing cookies on your website. ??

JavaScript cookies play a vital role in web development by storing small pieces of data locally on the user's device. This allows you to remember user preferences, track user interactions, and more. ??

Here's a simple function to set a cookie using JavaScript:

const setCookie = (name, value, days) => {
  const expirationDate = new Date(Date.now() + days * 24 * 60 * 60 * 1000).toUTCString();
  document.cookie = `${name}=${value}; expires=${expirationDate}; path=/`;
};

//calling the function like
setCookie('googtrans', '/fr/fr', 365);          


Let's break down the code:

  1. The function setCookie takes three parameters: name (cookie name), value (cookie value), and days (number of days until the cookie expires).
  2. It creates a new Date object to calculate the expiration date. The number of days provided is converted to milliseconds and added to the current date.
  3. The expires variable is set to a string containing the cookie expiration date in UTC format.
  4. Finally, the document.cookie property is set with the provided name, value, and expires values. The path=/ ensures the cookie is accessible across the entire website.

In this specific example, we are setting a cookie named googtrans with the value /fr/fr, which indicates French as the target language. This cookie will expire in 365 days.

Remember to adapt this code to your specific use case and project requirements. Also, be cautious about storing sensitive or personal information in cookies, as they can be accessed on the client-side.

Happy coding! ???? If you have any questions or suggestions, feel free to drop them in the comments below. Let's keep learning and growing together! ???? #webdevelopment #javascript #cookies #codingtips

要查看或添加评论,请登录

社区洞察

其他会员也浏览了