As HTTP is a stateless protocol i.e. all requests to the server are treated as new requests and there is no way to determine if a request comes from a user who already did a request before or if it is a new user.
A cookie is a small piece of information that the server stores in the client browser to recognize the user in the future. A cookie is sent every time, the same client sends a request to the server. JavaScript facilitates the features of both creating and retrieving cookie values.
How do cookies work in JavaScript?
When a request comes to the server, the application can attach a small information calls a cookie in response. If the client’s browser accepts the cookie then it stores this information on the client’s machine as plain text. When the client sends a new request browser will attach this information to the server with the request. The application can retrieve the cookie and can identify the user or client.
Restrictions of cookies
- A cookie can store a maximum of 4 kb of data.
- Cookies are specific to the domain.
- A browser can store max 20 cookies per domain.
To Create a Cookie:
document.cookie = "key = value";
To Retrieve a Cookie:
document.cookie
Example:
<!DOCTYPE html> <html> <head> </head> <body> <input type="button" value="set" onclick="setCookie()"> <input type="button" value="get" onclick="getCookie()"> <script> function setCookie() { document.cookie="username=John Miller"; } function getCookie() { if(document.cookie.length!=0) { var array=document.cookie.split("="); alert("Name="+array[0]+" "+"Value="+array[1]); } else { alert("No cookie available"); } } </script> </body> </html>