Javascript Cookies

Code Snippets Cookies


In this code snippet, we’ll learn how to add/get cookies with Javascript.

Cookies allow a website to store information about a user in the browser. This way if the site refreshes or the user leaves and comes back later the data can be preserved. Cookies also get sent along with requests to the server. A server can give the browser a session cookie after the user logs in. This way every time the user sends something to the server it can just check for a valid session to make sure the user is authorized to perform a certain action.

Note: Keep in mind that the cookies will get sent to the server with every request so you should store a minimal amount of data in them. If you need more space or you don’t need to send data to the server with every request consider using the browser local storage

Security considerations: If you plan on using cookies for authentication/authorization watch out for CSRF(Cross Site Request Forgery).

Let’s see the example below.


//Add a cookie://///////////////////////////////////////////
//window.document.cookie = "TestCookie=Test"; //window can be left out and it will still work. 
document.cookie = "TestCookie=Test"; // "cookie name"="value you want to store"

//Setting the expiration date of a cookie.              //Year, month, day
document.cookie = "TestCookie=Test; expires=" + new Date(3021, 0, 1).toUTCString(); //This cookie would last for a 1000 years.

//Get cookies:///////////////////////////////////////////////
//You will get all the cookies as a string.   

Resulting output:

Adding a cookie
Getting cookies

Leave a Reply

Your email address will not be published. Required fields are marked *

The following GDPR rules must be read and accepted:
This form collects your name, email and content so that we can keep track of the comments placed on the website. For more info check our privacy policy where you will get more info on where, how and why we store your data.

Advertisment ad adsense adlogger