In web development, a Cookie is a small piece of data sent by the server to the user's browser and stored locally. It is primarily used to identify users, save login states, and preferences. Based on the persistence of the Cookie, they can be divided into persistent Cookies and non-persistent Cookies.
Non-persistent Cookies (Session Cookies)
Non-persistent Cookies, also known as session Cookies, are stored in memory and automatically deleted when the browser is closed. Session Cookies are typically used to manage user session state, such as whether the user is logged into the website.
Creation Method:
javascriptdocument.cookie = "username=JohnDoe";
In this example, no expires or max-age attributes are set for the Cookie, meaning this Cookie is non-persistent and will be automatically deleted when the user closes the browser.
Persistent Cookies
Persistent Cookies are stored on the user's device and deleted only when the specified expiration time (Expires) or maximum age (Max-Age) is reached. This type of Cookie is suitable for saving user preferences, such as interface language and themes, which need to be retained even after the browser is closed.
Creation Method:
javascriptdocument.cookie = "username=JaneDoe; max-age=3600";
In this example, max-age=3600 indicates that this Cookie should expire after 3600 seconds. Alternatively, the expires attribute can be used to specify a specific expiration date:
javascriptdocument.cookie = "userprefs=darkmode; expires=Fri, 01 Jan 2023 00:00:00 GMT";
Summary
In summary, non-persistent Cookies are typically used for session management because they do not need to be stored on the user's device for long periods. Persistent Cookies are used to store user information that needs to be retained long-term, such as personalized settings. When creating these Cookies, the key distinction is whether the expires or max-age attributes are set.