Burger mobile menu

JavaScript: create, update and remove cookies

Piotr Elmanowski Piotr Elmanowski | Published: 1 Feb, 2017

Cookie - Icons made by Freepik from www.flaticon.com is licensed by CC 3.0 BY

If we want to create, update or remove cookies in JavaScript we must do a few very simple operations like I described below.

Step 1 – prepare an expiration date for a cookie

I usually use below function to prepare expiration date of the cookie. Function takes time in minutes as argument, adds it to current time, and returns expiration time and date (current time + minutes from argument):

Step 2 – Create a cookie

I create a cookie in very common way, like presented below. To set “expires” parameter I use above function:

Step 3 – Update cookie expiration date

As I mentioned on the beginning of the post, to update expiration date we must do the same things like in step 2, with new date. So it is not updating cookie but rewriting it. In the same way we can update/rewrite cookie value:

Step 4 – remove cookie

To remove a cookie we must update its expiration date, but we must set date somewhere in the PAST! Then automatically, cookie become expired and will be deleted by a browser. The best way is to set the date: 1 January 1970 – of course in right format: “Thu, 01 Jan 1970 00:00:01 GMT” (unix time).

I use usually below function to remove many cookies:

Code in this post is very simple. I wanted just to show you basic operations on cookies. Feel free to comment this post 🙂

Tags: ,


Scroll top
Loading
Zdjęcie w lewo Zdjęcie w prawo