• Home
  • HTML
    • HTML Introduction
    • HTML Basic
    • HTML Elements
    • HTML Attributes
    • HTML Headings
    • HTML Paragraphs
    • HTML Text Formatting
    • HTML Styles
    • HTML Comments
    • HTML Styles - CSS
    • HTML Links
    • HTML Images
    • HTML Tables
    • HTML Lists
    • HTML Block and Inline Elements
    • HTML class Attribute
    • HTML Forms
    • HTML Media
  • CSS
    • Introduction of CSS
    • CSS Syntax
    • CSS Selectors
    • How To Add CSS
    • CSS Comments
    • CSS Colors
    • CSS Backgrounds
    • CSS Borders
    • CSS Margins
    • CSS Text
    • CSS Lists
    • CSS Tables
    • CSS Box Model
    • CSS Dimension
    • CSS Padding
    • CSS Border
    • CSS Margin
    • CSS Outline
    • CSS Cursors
    • CSS Overflow
    • CSS Units
    • CSS Visual Formatting
    • CSS Display
    • CSS Visibility
    • CSS Position
    • CSS Layers
    • CSS Float
    • CSS Alignment
    • CSS Pseudo-classes
    • CSS Pseudo-elements
    • CSS Media Types
    • CSS Sprites
    • CSS Opacity
    • CSS Attribute Selectors
    • CSS Validation
    • CSS3 Border
    • CSS3 Gradients
    • CSS3 Text Overflow
  • JavaScript
    • JS Introduction
    • JS Getting Started
    • JS Syntax
    • JS Variables
    • JS Generating Output
    • JS Data Types
    • JS Operators
    • JS Events
    • JS Strings
    • JS Numbers
    • JS If Else
    • JS Switch Case
    • JS Arrays
    • JS Sorting Arrays
    • JS Loops
    • JS Functions
    • JS Objects
    • JS DOM Nodes
    • JS DOM Selectors
    • JS DOM Styling
    • JS DOM Get Set Attributes
    • JS DOM Manipulation
    • JS DOM Navigation
    • JS Window
    • JS Screen
    • JS Location
    • JS History
    • JS Navigator
    • JS Dialog Boxes
    • JS Timers
    • JS Date and Time
    • JS Math Operations
    • JS Type Conversions
    • JS Event Listeners
    • JS Event Propagation
    • JS Borrowing Methods
    • JS Hoisting Behavior
    • JS Closures
    • JS Strict Mode
    • JS JSON Parsing
    • JS Error Handling
    • JS Regular Expressions
    • JS Form Validation
    • JS Cookies
    • JS AJAX Requests
    • JS ES6 Features
  • jQuery
    • jQuery Introduction
    • jQuery Syntax
    • jQuery Selectors
    • jQuery Events
    • jQuery Show/Hide
    • jQuery Fade
    • jQuery Slide
    • jQuery Animation
    • jQuery Stop
    • jQuery Chaining
    • jQuery Callback
    • jQuery Get/Set
    • jQuery Insert
    • jQuery Remove
    • jQuery CSS Classes
    • jQuery Style Properties
    • jQuery Dimensions
    • jQuery Traversing
    • jQuery Ancestors
    • jQuery Descendants
    • jQuery Siblings
    • jQuery Filtering
    • jQuery Ajax
    • jQuery Load
    • jQuery Get/Post
    • jQuery No-Conflict
  • PHP
    • PHP Introduction
    • PHP Install
    • PHP Syntax
    • PHP Comments
    • PHP Variables
    • PHP Echo / Print
    • PHP Data Types
    • PHP Strings
    • PHP Constants
    • PHP Operators
    • PHP If...Else...Elseif
    • PHP Switch
    • PHP Loops
    • PHP Functions
    • PHP Arrays
    • PHP Superglobals
    • PHP Date and Time
    • PHP Include
    • PHP File Handling
    • PHP File Upload
    • PHP Cookies
    • PHP Sessions
    • PHP Filters
    • PHP Callback Functions
    • PHP JSON
    • PHP Exceptions
    • PHP What is OOP
    • PHP Classes/Objects
    • PHP Constructor
    • PHP Destructor
    • PHP Access Modifiers
    • PHP Inheritance
    • PHP Abstract Classes
    • PHP Interfaces
    • PHP Traits
    • PHP Static Methods
    • PHP Namespaces
  • SQL
    • Introduction to SQL
    • SQL Create Command
    • SQL ALTER Command
    • SQL Truncate Drop Rename
    • INSERT SQL command
    • UPDATE SQL command
    • DELETE SQL command
    • SQL COMMIT command
    • SQL ROLLBACK command
    • SQL GRANT and REVOKE Command
    • SQL WHERE clause
    • SQL LIKE clause
    • SQL ORDER BY Clause
    • SQL Group By Clause
    • SQL HAVING Clause
    • SQL DISTINCT keyword
    • SQL AND OR operator
    • SQL Constraints
    • SQL Functions
    • SQL JOIN
  • Python
    • Getting started with Python
    • Introduction to IDLE
    • Python 2.x vs. Python 3.x
    • Syntax Rules and First Program
    • Numbers and Math Functions
    • Python Operators
    • Python Variables
    • Python Modules and Functions
    • Python Input and Output
    • Data Types in Python
    • String in Python
    • String Functions in python
    • Lists in Python
    • Utilizing List Elements by Iterating
    • Deleting List Elements & other Functions
    • Dictionaries in Python
    • Functions for Dictionary
    • Tuples in Python
    • Relational and Logical Operators
    • Conditional Statements in Python
    • Looping in Python
    • Define Functions in Python
    • Python-Introduction to OOP
    • Object Oriented Programming in Python
    • Classes in Python
    • The concept of Constructor
    • Destructors - Destroying the Object in Python
    • Inheritance in Python
    • Access Modifers in Python
    • Types of Inheritance
    • Method Overriding in Python
    • Polymorphism
    • static Keyword
    • Operator Overloading Python
    • Introduction to Error Handling
    • Exception Handling: try and except
    • Exeption Handling: finally
    • Exception Handling: raise
    • File Handling
    • Reading and Writing File
    • Introduction to Multithreading
    • Threading Module in Python
    • Thread Object
    • Lock Object
    • RLock Object
    • Event Object
    • Timer Object
    • Condition Object
    • Barrier Object
    • __name__ Variable in Python
    • Iterable and Iterator
    • yield Keyword
    • Python Generators
    • Python Closures
    • Python Decorators
    • @property Decorator in Python
    • Assert Statement
    • Garbage Collection
    • Shallow and Deep Copy
    • Introduction to Logging
    • Configure Log LEVEL, Format etc
    • Python Logging in a file
    • Python Logging Variable Data
    • Python Logging Classes and Functions
    • Python MySQL Introduction
    • Create Database - Python MySQL
    • Create Table - Python MySQL
    • Insert Data in Table
    • Select Data from Table
    • Update data in Table
    • Delete data from Table
    • Drop Table from Database
    • WHERE clause - Python MySQL
    • Order By clause - Python MySQL
    • Limit clause - Python MySQL
    • Table Joins - Python MySQL
  • MongoDB
    • MongoDB Introduction
    • Overview of MongoDB
    • MongoDB vs SQL Databases
    • Advantages of MongoDB
    • When to go for MongoDB
    • Data Modelling in MongoDB
    • Is MongoDB really Schemaless?
    • Installing MongoDB on Windows and Linux
    • Datatypes in MongoDB
    • Create and Drop Database in MongoDB
    • MongoDB: Creating a Collection
    • CRUD Operations in MongoDB
    • Data Relationships in MongoDB
    • Indexing in MongoDB
    • Sorting in MongoDB
    • Aggregation in MongoDB
    • Data Backup and Restoration in MongoDB
    • Sharding in MongoDB
    • Java Integration with MongoDB
  • Elixir
    • Elixir Overview
    • Elixir Environment
    • Elixir Basic Syntax
    • Elixir Data Types
    • Elixir Variables
    • Elixir Operators
    • Elixir Pattern Matching
    • Elixir Decision Making
    • Elixir Strings
    • Elixir Char Lists
    • Elixir Lists and Tuples
    • Elixir Keyword Lists
    • Elixir Maps
    • Elixir Modules
    • Elixir Aliases
    • Elixir Functions
    • Elixir Recursion
    • Elixir Loops
    • Elixir Enumerables
    • Elixir Streams
    • Elixir Structs
    • Elixir Protocols
    • Elixir File I/O
    • Elixir Processes
    • Elixir Sigils
    • Elixir Comprehensions
    • Elixir Typespecs
    • Elixir Behaviours
    • Elixir Errors Handling
    • Elixir Macros
    • Elixir Libraries
  • TypeScript
    • TypeScript Overview
    • Install TypeScript
    • First TypeScript Program
    • Type Annotation
    • TypeScript Variable
    • TypeScript Data Type Number
    • TypeScript Data Type String
    • TypeScript Data Type Boolean
    • TypeScript Arrays
    • TypeScript Tuples
    • TypeScript Enum
    • TypeScript Union
    • TypeScript Any Data Type
    • TypeScript Void Data Type
    • TypeScript Never Data Type
  • Home
  • JS Introduction
  • JS Getting Started
  • JS Syntax
  • JS Variables
  • JS Generating Output
  • JS Data Types
  • JS Operators
  • JS Events
  • JS Strings
  • JS Numbers
  • JS If Else
  • JS Switch Case
  • JS Arrays
  • JS Sorting Arrays
  • JS Loops
  • JS Functions
  • JS Objects
  • JS DOM Nodes
  • JS DOM Selectors
  • JS DOM Styling
  • JS DOM Get Set Attributes
  • JS DOM Manipulation
  • JS DOM Navigation
  • JS Window
  • JS Screen
  • JS Location
  • JS History
  • JS Navigator
  • JS Dialog Boxes
  • JS Timers
  • JS Date and Time
  • JS Math Operations
  • JS Type Conversions
  • JS Event Listeners
  • JS Event Propagation
  • JS Borrowing Methods
  • JS Hoisting Behavior
  • JS Closures
  • JS Strict Mode
  • JS JSON Parsing
  • JS Error Handling
  • JS Regular Expressions
  • JS Form Validation
  • JS Cookies
  • JS AJAX Requests
  • JS ES6 Features
Home >> javascript >> JS Cookies

JS Cookies

Welcome to another tutorial, here you will learn to create, read, update and delete a cookie in JavaScript.
 

What is a Cookie

A cookie can be defined as a small text file that lets you store a small amount of data (of nearly 4KB) on the user's computer. Cookies are mainly used in keeping track of information such as user preferences that the site can retrieve to personalize the page when a user visits the website next time.

The cookies are an old client-side storage mechanism. It was originally designed for use by server-side scripting languages such as PHP, ASP, etc. But, they can also be created, accessed, and modified directly using JavaScript, however, the process is a little bit complicated and messy.

Tip: Cookies can take up to 4 KB of space in the user's computer, including their name and values, cookies that exceed this length are trimmed to fit. therefore, each time the browser requests a page to the server, all the data in the cookie is automatically sent to the server within that request.

Warning: Beware of sensitive data such as a password or credit card information in cookies since it could potentially be manipulated by the malicious user so don’t store them.
 

Creating a Cookie in JavaScript

Cookies can be created, read, and deleted with the document.cookie property in JavaScript. All cookies associated with a document are represented by this property.

To create or store a new cookie, You can assign a name=value string to this property, to create or store a new cookie. This is shown below:

document.cookie = "firstName=Alex";

The values of cookies cannot contain commas, semicolons, or spaces. Therefore, you will need to use JavaScript's built-in function encodeURIComponent() to encode the values containing these characters before you can store them in the cookie. similarly, you will need to use the corresponding decodeURIComponent() function when you read the cookie value.

document.cookie = "name=" + encodeURIComponent("Nikolos Columbus");

By default, the current browser session is the lifetime of a cookie. This means it is lost when the user exits the browser. But, for a cookie to exist beyond the current browser session, its lifetime needs to be specified (in seconds) with a max-age attribute. This max-age attribute determines how long a cookie can exist on the user's system before it is deleted. For instance, the following cookie will live for 30 days.

document.cookie = "firstName=Christopher; max-age=" + 30*24*60*60;

The lifetime of a cookie can be specified with the expires attribute. This attribute makes use of an exact date (in GMT/UTC format) when the cookie should expire, instead of an offset in seconds.

document.cookie = "firstName=Christopher; expires=Thu, 31 Dec 2099 23:59:59 GMT";

Below is a function that sets a cookie with an optional max-age attribute. However, You can use the same function to delete a cookie by passing the value 0 for daysToLive parameter.

function setCookie(name, value, daysToLive) {
    // Encode value in order to escape semicolons, commas, and whitespace
    var cookie = name + "=" + encodeURIComponent(value);
    
    if(typeof daysToLive === "number") {
        /* Sets the max-age attribute so that the cookie expires
        after the specified number of days */
        cookie += "; max-age=" + (daysToLive*24*60*60);
        
        document.cookie = cookie;
    }
}

By default, a cookie is available to all web pages of a website in the same directory (or any subdirectories of that directory). But, when you specify a path, the cookie is available to all web pages in that specified path and all web pages in all subdirectories of the same path. For instance, if the path is set to / the cookie is available throughout a website, without which page creates the cookie.

document.cookie = "firstName=Christopher; path=/";

In addition, the domain attribute can be used if you want a cookie to be available across subdomains. By default, cookies are available only to the pages in the domain they were set in in a website/browser.

Note: if a cookie created by a page on ‘blog.example.com’ sets its path attribute to / and its domain attribute to ‘example.com’, the cookie is also available to all web pages on ‘backend.example.com’, and ‘portal.example.com’. But, you cannot share cookies outside its domain.

document.cookie = "firstName=Christopher; path=/; domain=example.com";

A boolean attribute named secure is also available. For instance, if this attribute is specified, the cookie will only be transmitted over a secure (i.e encrypted) connection such as HTTPS.

document.cookie = "firstName=Christopher; path=/; domain=example.com; secure";

 

Reading a Cookie

Reading a cookie is slightly more complex as a result of the document.cookie property returns a string containing a semicolon and a space-separated list of all cookies (i.e name=value pairs), for instance, firstName=John; lastName=Doe. However, this string doesn't contain the attributes such as expires, path, domain, etc., that might have been set for the cookie.

For you to get the individual cookie from this list, you need to make use of the split() method and break it into individual name=value pairs, and search for the specific name, as shown in the example below:

function getCookie(name) {
    // Split cookie string and get all individual name=value pairs in an array
    var cookieArr = document.cookie.split(";");
    
    // Loop through the array elements
    for(var i = 0; i < cookieArr.length; i++) {
        var cookiePair = cookieArr[i].split("=");
        
        /* Removing whitespace at the beginning of the cookie name
        and compare it with the given string */
        if(name == cookiePair[0].trim()) {
            // Decode the cookie value and return
            return decodeURIComponent(cookiePair[1]);
        }
    }
    
    // Return null if not found
    return null;
}

Let’s create one more function ‘checkCookie()’ that will check whether the firstName cookie is set or not, by utilizing the above getCookie() function. If the cookie is set then this function will display a greeting message, and if it is not then this function will prompt the user to enter their first name and store it in the cookie using our previously created setCookie() function.

function checkCookie() {
    // Get cookie using our custom function
    var firstName = getCookie("firstName");
    
    if(firstName != "") {
        alert("Welcome again, " + firstName);
    } else {
        firstName = prompt("Please enter your first name:");
        if(firstName != "" && firstName != null) {
            // Set cookie using our custom function
            setCookie("firstName", firstName, 30);
        }
    }
}

 

Updating a Cookie

The available way to update or modify a cookie is by creating another cookie with the same name and path as an existing one. Creating a cookie with the same name but a different path, then the existing one will add an additional cookie. 

Below is an example:

// Creating a cookie
document.cookie = "firstName=Christopher; path=/; max-age=" + 30*24*60*60;

// Updating the cookie
document.cookie = "firstName=Alexander; path=/; max-age=" + 365*24*60*60;


Deleting a Cookie

To delete a cookie, just set it once again by ensuring you use the same name, then specifying an empty or arbitrary value, and set its max-age attribute to 0. Do not forget, if you've specified a path, and domain attribute for the cookie, you'll also need to include them when deleting it.

// Deleting a cookie
document.cookie = "firstName=; max-age=0";

// Specifying path and domain while deleting cookie
document.cookie = "firstName=; path=/; domain=example.com; max-age=0";

But, to delete a cookie using the expires attribute, do it by setting its value (i.e the expiration date) to a date that has already passed, as demonstrated in the example below.

document.cookie = "firstName=; path=/; expires=Thu, 01 Jan 1970 00:00:00 GMT";

 

  • Prev
  • Next


-Advertisement-


DeveloperTutorial
[email protected] © 2022-2023 Developers Tutorial All rights reserved.

Follow Us

Facebook Twitter LinkedIn Printerest Reddit

Announcement

Its a big achivement for us, We make a partnership with TutorialWithExample.com for the better content of our users.

Still Need Help ?

Let us now about your issue and a Professional will reach you out.