Cookie Introduction
A cookie is data stored on the client side by a website to identify user identity (typically encrypted).
The HTTP protocol itself is stateless; to enable it to handle more complex logic, HTTP/1.1 introduced cookies to save state information.
Cookies are generated by the server and sent to the client for storage. When the client accesses again, the server can identify the client based on the cookie, enabling features such as personalized recommendations and login without account credentials or passwords.
- HTTP is a stateless protocol: It lacks memory capabilities for transaction processing. Each time a session between the client and server completes, the server does not save any session information. Every request is completely independent; the server cannot confirm the identity of the current visitor or determine if the sender of the previous request and the current sender are the same person. Therefore, to perform session tracking, both the server and the browser must actively maintain a state that informs the client whether two consecutive requests originate from the same browser. This state is implemented via cookies or sessions.
- Cookies are stored on the client: A cookie is a small piece of data sent by a server to the user's browser and saved locally. It will be carried and sent back to the server when the browser makes another request to the same server in the future.
- Cookies cannot cross domains: Each cookie is bound to a single domain and cannot be accessed or used under other domains. First-level domains and second-level domains are allowed to share usage (relying on the
domainattribute).
Typical Usage Scenarios
- Store user information for already logged-in users in cookies to achieve password-free login.
- Save user preferences, themes, and other setting information in cookies.
- Use cookies to store sessions or tokens. When sending requests to the backend, include the cookie so that the backend can retrieve the session or token. This solves the problems brought by the stateless nature of the HTTP protocol.
- Record and analyze user behavior using cookies. Save the duration a user spends on a specific page in a cookie and pass it to the backend.
Considerations When Using Cookies
- Since they are stored on the client, they can be easily tampered with; therefore, verify their legitimacy before use.
- Do not store sensitive data, such as user passwords or account balances.
- Use
HttpOnlyto improve security to a certain extent. - Minimize the size of cookies; the amount of storable data should not exceed 4KB.
- Set the correct
domainandpathto reduce data transmission. - Cookies cannot cross domains.
- A browser can store at most 20 cookies per website, and generally allows storing only 300 cookies in total.
- Mobile browsers have poor support for cookies; since sessions often rely on cookies for implementation, tokens are commonly used instead on mobile devices.