How to set a cookie in JavaScript

Setting cookies in JavaScript enables persistent data storage across browser sessions, perfect for user preferences, authentication tokens, and tracking information. As the creator of CoreUI with over 25 years of JavaScript experience, I’ve used cookies extensively in production applications for session management and user experience personalization. The most straightforward approach uses document.cookie with proper formatting for cookie name, value, expiration, and security options. This method provides reliable cross-session data storage while maintaining compatibility across all browsers.

Use document.cookie to set cookies with proper formatting for name, value, expiration, and security options.

document.cookie = 'username=JohnDoe; expires=Fri, 31 Dec 2024 23:59:59 GMT; path=/'

This code sets a cookie named ‘username’ with value ‘JohnDoe’ that expires on December 31, 2024, and is accessible across the entire website. The cookie string format includes the name-value pair followed by optional attributes like expiration date, path scope, and security settings. The browser automatically manages cookie storage and will include this cookie in future requests to the same domain.

Best Practice Note:

This is the cookie management approach we use in CoreUI applications for user preference storage. Always set appropriate expiration dates and consider using secure flags (Secure; HttpOnly) for sensitive data to enhance security.


Speed up your responsive apps and websites with fully-featured, ready-to-use open-source admin panel templates—free to use and built for efficiency.


About the Author

Subscribe to our newsletter
Get early information about new products, product updates and blog posts.

Answers by CoreUI Core Team