Cookie expires is not defined error javascript

cookie expires is not defined error javascript

Due to an obscure bug in the underlying WinINET InternetGetCookie implementation, IE's document.cookie will not return a cookie if it was set with a path. Note: Cookies expire automatically based on an expiration date that can be set in code. If no expiration date is set, the cookie will be deleted as soon as. Specifies the Date object to be the value for the Expires Set-Cookie attribute. By default, no expiration is set, and most clients will consider this a “non-. cookie expires is not defined error javascript

watch the video

Cookie Expiration: Set When to Stop Accepting One Click Upsells

Alert does not stay closed on refresh

Hi @quinex,

There must be some confusion, we don’t really provide customization here in the forum. What was provided is just an idea, but not to solve the customization issue. We don’t pick who will be given with the code, it depends on to which it is being applied. For example, let’s say a user has a simple issue and it’s not product related, but it happens that we, as support, are familiar with it based on one’s experience, then we can simply provide some guide and what was provided has no guarantee to work for anyone, and t’s always personal advice. On another example, there is user issue that we don’t understand and need further customization. Then that’s when we can’t provide some code or guidance since we’re not familiar with it and it’s not part of our product features.

Now let’s take the client as a sample where you said you’re able to get a code, that client already implemented his own Cookie library which works okay on his site. And that’s something we don’t implement or familiar with, but given it’s already set up, cookie expires is not defined error javascript, then what we just provided is a simple code to properly use that said library. Which again, will or may not work depending on setup, and it happens to work on his setup.

Now, your issue is not with the code, it’s the issue with cookie library that isn’t present from your site. In which clearly visible from the error you’re getting, cookie expires is not defined error javascript. And with that, we as a support aren’t familiar with its implementation and we can’t really answer that. We initially check the client’s site if it’s an easy one or if we’re familiar with it, then offer some guidance if it’s just a very simple one.

Again, as a summary, cookie expires is not defined error javascript, we may able to provide some guidance on an issue in which personally, we as support already understand even if it’s not part of our theme/plugin features. But it’s strict that we don’t provide support outside the product we offers.

Thanks for understanding.

Sessions and Cookies ¶

Sessions and cookies allow data to be persisted across multiple user requests. In plain PHP you may access them through the global variables andrespectively. Yii encapsulates sessions and cookies as objects and thus allows you to access them in an object-oriented fashion with additional useful enhancements.

Sessions ¶

Like requests and responses, you can get access to sessions via the application component which is error system cmos checksum bad instance of yii\web\Session, by default.

Opening and Closing Sessions ¶

To open and close a session, you can do the following:

You can call open() and close() multiple times without causing errors; internally the methods will first check if the session is already open.

Accessing Session Data ¶

To access the data stored in session, you can do the following:

Info: When you access session data through the component, a session will cookie expires is not defined error javascript automatically opened if it has not been done so before. This is different from accessing session data throughwhich requires an explicit call of .

When working with session data that are arrays, the component has a limitation which prevents you from directly modifying an feedforward error correction amplifier element. For example,

You can use one of the following workarounds to solve this problem:

For better performance and code readability, we recommend the last workaround. That is, instead of storing an array as a single session variable, you store each array element as a session variable cookie expires is not defined error javascript shares the same key prefix with other array elements.

Custom Session Storage ¶

The default yii\web\Session class stores session data as files on the server. Yii also provides the following session classes implementing different session storage:

All these session classes support the same set of API methods. As a result, you can switch to a different session storage class without the need to modify your application code that uses sessions.

Note: If you want to access session data via while using custom session storage, you must make sure that the session has already been started by yii\web\Session::open(). This is because custom session storage handlers are registered within this method.

Note: If you use a custom session storage you may need to configure the session garbage collector explicitly. Some installations of PHP (e.g. Debian) use a garbage collector probability of 0 and clean session files offline in a cronjob. This process does not apply to your custom storage so you need to configure yii\web\Session::$GCProbability to use a non-zero value.

To learn how to configure and use these component classes, please refer to their API documentation. Below is an example showing how to configure yii\web\DbSession in the application configuration to use a database table for session storage:

You also need to create the following database table to store session cookie expires is not defined error javascript 'BLOB' refers to the BLOB-type of your preferred DBMS. Below are the Cookie expires is not defined error javascript types that can be used for some popular DBMS:

  • PostgreSQL: BYTEA

Note: According to the php.ini setting ofyou may need to adjust the length of the column. For example, ifyou should use a length 64 instead of 40.

Alternatively, this can be accomplished with the following migration:

Flash Data ¶

Flash data is a special kind of session data which, once set in one request, will only be available during the next request and will be automatically deleted afterwards. Flash data is most commonly used to implement messages that should only be displayed to end users once, such as a confirmation message displayed after a user successfully submits a form.

You can set and access flash data through the application component. For example,

Like regular session data, you can store arbitrary data as flash data.

When you call yii\web\Session::setFlash(), it will overwrite any existing flash data that has the same name. To append new flash data to an existing message of the same name, you may call yii\web\Session::addFlash() instead. For example:

Note: Try not to use yii\web\Session::setFlash() together with yii\web\Session::addFlash() for flash data of the same name. This is because the latter method will automatically turn the flash data into an array so that it can append new flash data of the same name. As a result, when you call yii\web\Session::getFlash(), you may find sometimes you are getting an array while sometimes you are getting a string, depending on the order of the invocation of these two methods.

Tip: For displaying Flash messages you can use yii\bootstrap\Alert widget in the following way:

Cookies ¶

Yii represents each cookie as an object of yii\web\Cookie. Both yii\web\Request and yii\web\Response maintain a collection of cookies via the property named. The cookie collection in the former represents the cookies submitted in a request, while the cookie collection in the latter represents the cookies that are to be sent to the user.

The part of the application dealing with request and response directly is controller. Therefore, cookies should be read and sent in controller.

Reading Cookies ¶

You can get the cookies in the current request using the following code:

Sending Cookies ¶

You can send cookies to end users using the following code:

Besides the name, value properties shown in the above examples, the yii\web\Cookie class also defines other properties to fully represent all available cookie an error 713 information, such as domain, expire. You may configure these properties as needed to prepare a cookie and then add it to the response's cookie collection.

Cookie Validation ¶

When you are reading and sending cookies through the and components as shown in the last two subsections, you enjoy the added security of cookie validation which protects cookies from being modified on the client-side. This is achieved by signing each cookie with a hash string, which allows the application to tell if a cookie expires is not defined error javascript has been modified on the client-side. If so, the cookie will NOT be accessible through the cookie collection of the component.

Note: Cookie validation only protects cookie values from being modified. If a cookie fails the validation, you may still access it through. This is because third-party libraries may manipulate cookies in their own way, which does not involve cookie validation.

Cookie validation is enabled by default. You can disable it by setting the yii\web\Request::$enableCookieValidation property to bealthough we strongly recommend you do not do so.

Note: Cookies that are directly read/sent via and will NOT be validated.

When using cookie validation, you must specify a yii\web\Request::$cookieValidationKey that will be used to generate the aforementioned hash strings. You can do so by configuring the component in the application configuration:

Info: cookieValidationKey is critical to your application's security. It should only be known to people you trust. Do not cookie expires is not defined error javascript it in the version control system.

Security settings ¶

Both yii\web\Cookie and yii\web\Session support the following security flags:

httpOnly ¶

For better security, the default value of yii\web\Cookie::$httpOnly and the 'httponly' parameter of yii\web\Session::$cookieParams is set to. This helps mitigate the risk of a client-side script accessing the protected cookie (if the browser supports it). You may read the HttpOnly wiki article for more details.

secure ¶

The purpose of the secure flag is to prevent cookies from being sent in clear text. If the browser supports the secure flag it will only include the cookie when the request is sent over a secure (TLS) connection, cookie expires is not defined error javascript. You may read the SecureFlag wiki article for more details.

sameSite ¶

Starting with Yii 2.0.21 the yii\web\Cookie::$sameSite setting is supported. It requires PHP version 7.3.0 or higher. The purpose of the setting is to prevent CSRF (Cross-Site Request Forgery) attacks. If the browser supports the setting it will only include the cookie according to the specified policy ('Lax' or 'Strict'). You may read the SameSite wiki article for more details. For better security, an exception will be thrown if is used with an unsupported version of PHP. To use this feature across different PHP versions check the version first. E.g. php [

] > Note: Since not all browsers support the setting yet, it is still strongly recommended to also include additional CSRF protection.

Session php.ini settings ¶

As noted in PHP manual, has important session security settings. Please ensure recommended settings are applied. Especially that is not enabled by default in PHP installations. This setting can also be set with yii\web\Session::$useStrictMode.

Understanding Cookies and Implementing them in Node.js

Websites usually store a small amount of data on the browsers. There are three main kinds of browser-based storage: session storage, local storage, and cookie storage. This guide will discuss what a cookie is, how it works and how to use HTTP cookies in a Node.js application.


What are cookies?

A cookie is usually a tiny text file stored in your web browser. A cookie was initially used to store information about the websites that you visit. But with the advances in technology, a cookie can track your web activities and retrieve your content preferences. I am sure, at some point, you have seen a pop-up screen similar to the one shown below.

Accept cookies website popup

This will help the website you have visited to know more about you and customize your future experience.

For example;

  • Cookies save your language preferences. This way, when you visit that website in the future, the language you used will be remembered.

  • You have most likely visited an e-commerce website. When you include items into your shopping cart, a cookie will remember your choices. Your shopping list item will still be there whenever you revisit the site. Basically, a cookie is used to remember data from the user.

Therefore, cookies are small strings that contain key-value pairs of information sent from the webserver to the browser to get information about the user. The browser will then save them locally, cookie expires is not defined error javascript. This way, subsequent requests can be made to the server to immediately update user content on the website depending on the previous requests that a user made to the server. A cookie is HTTP generated; thus, called an HTTP cookie.

A brief history of cookies

The first HTTP cookie was created in 1994 by Lou Montulli, an employee of Netscape Communications, the company that created the Netscape browser. Lou was creating an online store for a company that claimed that their servers were getting full from cookie expires is not defined error javascript each user’s shopping cart data.

Lou, therefore, had to figure out how to store the contents of the shopping cart locally. He came up with an idea to save the shopping cart info on the user’s computer to save server space. He borrowed the concept of HTTP cookies from a computing token called the magic cookie which was used to identify a user when logging into a system.

Lou recreated this concept and implemented it in a web browser, cookie expires is not defined error javascript. In 1994, the Netscape browser implemented cookies, cookie expires is not defined error javascript, followed by Internet Explorer in 1995 and that marked the birth of HTTP cookies.

How cookies work

When a user visits a cookie-enabled website for the first time, the browser will prompt the user that the web page uses cookies and request the user to accept cookies to be saved on their computer. Typically, when a makes a user request, the server responds by sending back a cookie (among many other things).

This cookie is going to be stored in the user’s browser. When a user visits the website or sends another request, that request will be sent back together with the cookies. The cookie will have certain information about the user that the server can use to make decisions on any other subsequent requests.

A perfect example is accessing Facebook from a browser. When you want to access your Facebook account, you have to log in with the correct credentials to be granted the proper access. But in this case, it would be tiresome to continuously log in to Facebook every time.

When you first make a login request and the server verifies your credentials, the server will send your Facebook account content. It will also send cookies to your browser. The cookies are then stored on your computer and submitted to the server with every request you make to that website. A cookie will be saved with an identifier that is unique to that user.

When you revisit Facebook, the request you make, the saved cookie, and the server will keep track of your login session and cookie expires is not defined error javascript who you are and thus keep you logged in.

The different types of cookies include:

  • Session cookies - store user’s information for a short period. When the current session ends, that session cookie is deleted from the user’s computer.

  • Persistent cookies - a persistent cookie lacks expiration date. It is saved as long as the webserver administrator sets it.

  • Secure cookies - are used by encrypted websites to offer protection from any possible threats from a hacker.

  • Third-party cookies - are used by websites that show ads on their pages or track website traffic. They grant access to external parties to decide the types of ads to show depending on the user’s previous preferences.

The main difference between a session and a cookie

The major difference between sessions and cookies is that sessions live on the server-side (the webserver), and cookies live on the client-side (the user browser). Sessions have sensitive information such as usernames and passwords. This is why they are stored on the server. Sessions can be used to identify and validate which user is making a request.

As we have explained, cookies are stored in the browser, and no sensitive information can be stored in them. They are typically used to save a user’s preferences.

Setting up cookies with Node.js

Let’s dive in and see how we can implement cookies using Node.js. We will create and save a cookie in the browser, update and delete a cookie.

Go ahead and create a project directory on your computer. Initialize Node.js using to generate a file to manage Node.js project dependencies.

We will use the following NPM packages:

  • Express - this is an opinionated server-side framework for Node.js that helps you create and manage HTTP server REST endpoints.

  • cookie-parser - cookie-parser looks at the headers in between the client and the server transactions, reads these headers, parses out the cookies being sent, and saves them in a browser. In other words, cookie-parser will help us create and manage cookies depending on the request a user makes to the server.

Run the following command to install these packages:

We will create a simple example to demonstrate how cookies work.

Step 1 - Import the installed packages

To set up a server and save cookies, import the cookie parser and express modules to your project. This will make the necessary functions and objects accessible.

Step - 2 Get your application to use the packages

You need to use the above modules as middleware inside your application, as shown below.

This will make your application use the cookie parser and Express modules.

Step - 3 Set a simple route to start the server

We use the following code to set up a route for the homepage:

Step 4 - Set a port number

This is the port number that the server should listen to when it is running. This will help us access our server locally. In this example, the server will listen to portas shown below.

Now we have a simple server set. Run to test if it is working.

Running an Express server

And if you access the localhost on port 8000 (), you should get an HTTP response sent by the server. Now we’re ready to start implementing cookies.

Setting cookies

Let’s add and that will help us create, update and delete a cookie.

Step 1 - Set a cookie

We will set a route that will save a cookie in the browser. In this case, the cookies will be coming from the server to the client browser. To do this, use the object and pass as the method, i.e, cookie expires is not defined error javascript. as shown below.

When the above route is executed from a browser, cookie expires is not defined error javascript, the client sends a get request to the server. But in this case, the server will respond with a cookie and save it in the browser.

Go ahead and run to serve the above endpoint. Open your browser and access the route.

To confirm that the cookie was saved, go to your browser’s inspector tool 🡆 select the application tab 🡆 cookies 🡆 select your domain URL.

Saving a cookie in the browser

Step 2 - Using the req.cookies method to check the saved cookies

If the server sends this cookie to the browser, this means we can iterate the incoming requests through and check the existence of a saved cookie. You can log this screensaver error windows xp crfxfnm to the console or send the cookie request as a response to the browser. Let’s do that.

Again run the server using to expose the above route () and you can see the response on the browser.

A saved cookie

As well as on your console logs.

Cookie saved in the console

Step 3 - Secure cookies

One precaution that you should always take when setting cookies is security. In the above example, the cookie can be deemed insecure.

For example, you can access this cookie on a browser console using JavaScript (). This means that this cookie is exposed and can be exploited through cross-site scripting.

You can see the cookie when you open the browser inspector tool and execute the following in the console.

The saved cookie values can be seen through the browser console.

Browser console

As a precaution, you should always try to make your cookies inaccessible on the client-side using JavaScript.

We can add several attributes to make this cookie more secure.

  • ensures that a cookie is not accessible using the JavaScript code. This is the most crucial form of protection against cross-scripting attacks.
  • A attribute ensures that the browser will reject cookies unless the connection happens over HTTPS.
  • attribute improves cookie security and avoids privacy leaks.

By default, was initially set to (). This allowed third parties to track users across sites. Currently, it is set to () meaning a cookie is only set when the domain in the URL of the browser matches the domain of the cookie, thus eliminating third party’s domains. can also be set to (). This will restrict cross-site sharing even between different domains that the same publisher owns.

  • You can also add the maximum time you want a cookie to be available on the user browser. When the set time elapses, the cookie will be automatically deleted from the browser.

Read this guide to learn more attributes and how you can use them in JavaScript and Node.js.

In this case, we are accessing the server on localhost, which uses a non-HTTPS secure origin. For the sake of testing the server, you can set. However, always use value when you want cookies to be created on an HTTPS secure origin.

If you run the server again () and navigate to on the browser, you can see that the values of the cookie have been updated with security values.

Cookies updated security values

Furthermore, you cannot access the cookie using JavaScript, i.e.

Cookie not accessed with JavaScript

Step 4 - Deleting a cookie

Typically, cookies can be deleted from the browser depending on the request that a user makes. For example, if cookies are used for login purposes, when a user decides to log out, the request should be accompanied by a delete an error event occured. eventid 0x80001778 is how we can delete the cookie we have set above in this example. Use to clear all cookies.

Openand you will see that the saved cookie has been deleted.

A saved cookie deleted

A use case: How to authenticate a user with cookies

Let’s have a simple authentication example that uses cookies to grant access when a user first logs in to a website. This example will show you how to use cookies to process a simple authentication.

Step 1 - The project structure

Create a new project folder and initialize the project with. Set up your project, as shown below in this structure.

Step:2 Setting the project dependencies

This project will use the following NPM packages.

  • Cookie-parser - For parsing cookies from the response object to the request object.
  • Express - Web framework for Node.js
  • Ejs - For rendering the views.
  • Helmet - For secure HTTP requests.
  • Nodemon - For restarting the server during development.

Install the above packages using the command below.

Since we are using to watch the server files, go ahead and change the tag inside your file, as shown below.

This will help us start the server withand will watch our file. It will restart the server whenever you make, and save changes.

Step 3 - Setting up the server

In this step, we will set up our server. The comments included inside the different cookie expires is not defined error javascript on the code will help you figure things out if you get stuck.

Step 4 - Setting the EJS views

The server will render the following EJS views.

  1. A home page - the first page the user will access when a request is made to the endpoint .
  1. A login page- once a user selects on the home page, they will be redirected to a login page at endpoint .
  1. A welcome page- If a user logs in successfully, he/she will be redirected to webpage on the endpoint. From here, a user can log out and be redirected back to the .

Next, add some CSS to style the above views.

Step 5 - Running the application

To start the server, run .

A login server running

Step 6 - Testing the application

Let’s now test the application and see if everything is working.

  • Open in a browser, and you will be served this .

A Home page

  • Clicking the link on the will redirect you to this .

A login page

  • We then need to enter the and. Since this is a simple demonstration, cookie expires is not defined error javascript, we have not used a database to save the login credentials. We have defined them in the file:

Use as the username and as the password. If the credentials are correct, you will be served with this welcome page.

A welcome page

We are using cookies here, so when logs in successfully, a cookie with Bob’s will be saved on his browser. Go to your browser inspector tool 🡆 application 🡆cookies 🡆 select your domain .

Bob login cookie

Now that this cookie is saved, Bob will not have to provide login credentials again when he revisits the site. Go ahead and try if this works when you access the home route ().

When Bob chooses to the server will send a response to clear the saved cookie in the browser.

Try to log out and see what happens.

Logout clear cookies

The saved cookie will be cleared, cookie expires is not defined error javascript, and thus Bob will need to log in again when he wants to access the pages of this domain.

What are cookies used for?

As a developer, you might wonder how cookies are helpful and why developers need to use them. Here are a few use cases that explain the importance of collecting and saving user preferences, as well as other useful information in a cookie.

Session cookie

It tracks the sessions a user has interacted with within a website. Any kind of information that the server needs to remember about you is included in session management. For example, in shopping websites, every cookie is unique to a specific user. As discussed, an e-commerce website can use cookies to store your shopping cart’s contents.

In online games, cookies may be used to store your scores.


This saves user preferences such as themes, languages, and different website settings. In other words, cookie expires is not defined error javascript, cookies can be used to personalize and make sure the user gets the experience they are looking for.

Tracking user activities

Cookies can track any user behavior on a website. This includes the pages you access, the links you click, and how long you interact with a web page. This tracking is mostly done by third parties to analyze a website. Since a cookie is specific to one user, it can be used to determine how many unique users visit a website.


Note that cookies are not intended for transmitting sensitive data. As a developer, you must ensure that the response you send to a client does not contain sensitive information such as passwords. A cookie is saved on a browser and can, therefore, be manipulated if it falls in the wrong hands.

There are cookie regulations that make sure cookies are not used in the wrong way. These guidelines also restrict the type of data that a cookie can get from a user to avoid compromising user privacy.

According to GDPR, internet identifiers such as cookies are considered personal data, and organizations can only exploit them with the client’s permission. This the reason why cookie opt-in prompts are json error at index 55844 syntax error common when you visit a website.

I hope this guide helps you to understand what cookies are and how to use them in a Node.js web application in the correct way. Happy coding.

Peer Review Contributions by: Wanja Mike


Note: This page was generated from the cookie-session README.

NPM VersionNPM DownloadsBuild StatusTest Coverage

Simple cookie-based session middleware.

A user session can be stored in two main ways with cookies: on the server or on the client. This module stores the session data on the client within a cookie, while a module like express-session stores only a session identifier on the client within a cookie and stores the session data on the server, typically in a database.

The following points can help you choose which to use:

  • does not require any database / resources on the server side, though the total session data cannot exceed the browser’s max cookie size.
  • can simplify certain load-balanced scenarios.
  • can be used to store a “light” session and include an identifier to look up a database-backed secondary store to reduce database lookups.


This is a Node.js module available through the npm registry. Installation is done using the command:



Create a new cookie session middleware with the provided options. This middleware will attach the property towhich provides an object representing the loaded session. This session is either a new session if no valid session was provided in the request, or a loaded session from the request.

The middleware will automatically add a header cookie expires is not defined error javascript the response if the contents of were altered. Note that no header will be in the response (and thus no session created for a specific user) unless there are contents in the session, so be sure to add something to as soon as you have identifying information to store for the session.


Cookie session accepts these properties in the options object.


The name of the cookie to set, defaults to .


The list of keys to use to sign & verify cookie values, or a configured instance. Set cookies are always signed withwhile the other keys are valid for verification, allowing for key rotation. If a instance is provided, it can be used to change signature parameters like the algorithm of the signature.


A string which will be used as single key if is not provided.

Cookie Options

Other options are passed to and allowing you to control security, domain, path, and signing among other settings.

The options can also contain any of the following (for the full list, see cookies module documentation:

  • : a number representing the milliseconds from for expiry
  • : a object indicating the cookie’s expiration date (expires at the end of session by default).
  • : a string indicating the path of the cookie ( by default).
  • : a string indicating the domain of the cookie (no default).
  • : a boolean or string indicating whether the cookie is a “same site” cookie ( by default). This can be set to,or (which maps to ).
  • : a boolean indicating whether the cookie is only to be sent over HTTPS ( by default for HTTP, by default for HTTPS). If this is set to and Node.js is not directly over a TLS connection, be sure to read how to setup Express behind proxies or the cookie may not ever set correctly.
  • : a boolean indicating whether the cookie is only to be sent over HTTP(S), and not made available to client JavaScript ( by default).
  • : a boolean indicating whether the cookie is to be signed ( by default).
  • : a boolean indicating whether to overwrite previously set cookies of the same name ( by default).


Represents the session for the given request.


Is if the session has been changed during the request.


Is if the session is new.


Determine if the session has been populated with data or is empty.


Represents the session options for the current request. These options are a shallow clone of what was provided at middleware construction and can be altered to change cookie setting behavior on a per-request basis.

Destroying a session

To destroy a session simply set it to :

Saving a session

Since the entire contents of the session is kept in a client-side cookie, the session is “saved” by writing a cookie out in a response header. This is done automatically if there has been a change made to the session when the Node.js response headers are being written to the client and the session was not destroyed.


Simple view counter example

Per-user sticky max age

Extending the session expiration

This module does not send a header if the contents of the session have not changed. This means that to extend the expiration of a session in the user’s browser (in response to user activity, for example) some kind of modification to the session needs be made.

Using a custom signature algorithm

This example shows creating a custom instance as the option to provide keys and additional signature configuration.

Usage Limitations

Max Cookie Size

Because the entire session object is encoded and stored in a cookie, it is possible to exceed the maximum cookie size limits on different browsers, cookie expires is not defined error javascript. The RFC6265 specification recommends that a browser SHOULD allow

At least 4096 bytes per cookie (as measured by the sum of the length of the cookie’s name, value, and attributes)

In practice this limit differs slightly across browsers. See a list of browser limits here. As a rule of thumb don’t exceed 4093 bytes per domain.

If your session object is large enough to exceed a browser limit when encoded, in most cases the browser will refuse to store the cookie. This will cause the following requests from the browser to np 7161 error 1d a) not have any session information or b) use old session information that was small enough to not exceed the cookie limit.

If you find your session object is hitting these limits, it is best to consider if data in your session should be loaded from a database on the server instead of transmitted to/from the browser with every request. Or move to an alternative session strategy



JavaScript Cookies

❮ PreviousNext ❯

Cookies let you store user information in web pages.

What are Cookies?

Cookies are data, cookie expires is not defined error javascript, stored in small text files, on your computer.

When a web server has sent a web page to a browser, the connection is shut down, and the server forgets everything about the user.

Cookies were invented to solve the problem "how to remember information about the user":

  • When a user visits a web page, his/her name can be stored in a cookie.
  • Next time the user visits the page, the cookie "remembers" his/her name.

Cookies are saved in name-value pairs like:

When a browser requests a web page from a server, cookies belonging to the page are added to the request. This way the server gets the necessary data to "remember" information about users.

None of the examples below will work if your browser has local cookies support turned off.

Create a Cookie with JavaScript

JavaScript can create, read, and delete cookies with the property.

With JavaScript, a cookie can be created like this:

document.cookie = "username=John Doe";

You can also add an expiry date (in UTC time). By default, the cookie is deleted when the browser is closed:

document.cookie = "username=John Doe; expires=Thu, 18 Dec 2013 12:00:00 UTC";

With a path parameter, you can tell the browser what path the cookie belongs to. By default, the cookie belongs to the current page.

document.cookie = "username=John Doe; expires=Thu, 18 Dec 2013 12:00:00 UTC; path=/";

Read a Cookie with JavaScript

With JavaScript, cookies can be read like this:

will return all cookies in one string much like: cookie1=value; cookie2=value; cookie3=value;

Change a Cookie with JavaScript

With JavaScript, you can change a cookie the same way as you create it:

document.cookie = "username=John Smith; expires=Thu, 18 Dec 2013 12:00:00 UTC; path=/";

The old cookie is overwritten.

Delete a Cookie with JavaScript

Deleting a cookie is very simple.

You don't have to specify a cookie value when you delete a cookie.

Just set the expires parameter to a past date:

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

You should define the cookie path to ensure that you delete the right cookie.

Some browsers will not let you delete a cookie if you don't specify the path.

The Cookie String

The property looks like a normal text string. But it is not.

Even if you write a whole cookie string to document.cookie, when you read it out again, you can only see the name-value pair of it.

If you set a new cookie, older cookies are not overwritten. The new cookie is added to document.cookie, so if you read document.cookie again you will get something like:

cookie1 = value; cookie2 = value;


If you want to find the value of one specified cookie, you must write a JavaScript function that searches for the cookie value in the cookie string.

JavaScript Cookie Example

In the example to follow, we will create a cookie that stores the name of a visitor.

The first time a visitor arrives to the web page, cookie expires is not defined error javascript, he/she will be asked to fill in his/her name. The name is then stored in a cookie.

The next time the visitor arrives at the same page, he/she will get a welcome message.

For the example we will create 3 JavaScript functions:

  1. A function to set a cookie value
  2. A function to get a cookie value
  3. A function to check a cookie value

A Function to Set a Cookie

First, we create a that stores the name of the visitor in a cookie variable:


function setCookie(cname, cvalue, exdays) {
  const d = new Date();
  d.setTime(d.getTime() + (exdays*24*60*60*1000));
  let expires = "expires="+ d.toUTCString();
  document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/";

Example explained:

The parameters of the function above are the name of the cookie (cname), the value of the cookie (cvalue), and the number of days until the cookie should expire (exdays).

The function sets a cookie by adding together the cookiename, the cookie value, and the expires string.

A Function to Get a Cookie

Then, we create a that returns the value of a specified cookie:


function getCookie(cname) {
  let name = cname + "=";
  let decodedCookie = decodeURIComponent(document.cookie);
  let ca = decodedCookie.split(';');
  for(let i = 0; i <ca.length; i++) {
    let c = ca[i];
    cookie expires is not defined error javascript (c.charAt(0) == ' ') {
      c = c.substring(1);
    if (c.indexOf(name) == 0) {
      return c.substring(name.length, c.length);
  return "";

Function explained:

Take the cookiename as parameter (cname).

Create a variable (name) with the text to search for (cname + "=").

Decode the cookie string, to handle cookies with special characters, e.g. '$'

Split document.cookie on semicolons into an array called ca (ca = decodedCookie.split(';')).

Loop through the ca array (i = 0; i < ca.length; i++), cookie expires is not defined error javascript, and read out each value c = ca[i]).

If the cookie is found (c.indexOf(name) == 0), return the value of the cookie (c.substring(name.length, c.length).

If the cookie is not found, return "".

A Function to Check a Cookie

Last, we create the function that checks if a cookie is set.

If the cookie is set it will display a greeting.

If the cookie is not set, it will display a prompt box, asking for the name of the user, and stores the username cookie for 365 days, by calling the function:


function checkCookie() {
  let username = getCookie("username");
  if (username != "") {
   alert("Welcome again " + username);
  } else {
    username = prompt("Please enter your name:", "");
    if (username != "" && username != null) {
      setCookie("username", username, 365);

All Together Now


function setCookie(cname, cvalue, exdays) {
  const d = new Date();
  d.setTime(d.getTime() + (exdays * 24 * 60 * 60 * 1000));
  let expires = "expires="+d.toUTCString();
  document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/";

function getCookie(cname) {
  let name = cname + "=";
  let ca = document.cookie.split(';');
  for(let i = 0; i < ca.length; i++) {
    let c = ca[i];
    while (c.charAt(0) == ' ') {
      c = c.substring(1);
    if (c.indexOf(name) == 0) {
      return c.substring(name.length, c.length);
  return "";

function checkCookie() {
  let user = getCookie("username");
  if (user != "") {
    alert("Welcome again " + user);
  } else {
    user = prompt("Please enter your name:", "");
    if (user != "" && user != null) {
      setCookie("username", user, 365);

Try it Yourself »

The example above runs the function when the page loads.

❮ PreviousNext ❯


Leave a Comment