I'm noticing multiple repeated entries appearing when I try to set the cookie - what could be causing

Currently, I am utilizing the library js-cookie instead of my previous use of jquery.cookie. I have encountered an issue related to duplicating cookie entries. There are occasions when I invoke the following method:

Cookies.set('my-cookie-name', 'value', {'path': '/'});

Although I am certain that this method is only called once in my code base, I sometimes end up with:

---------------------------------------------------------------
Name               Value     Domain              Path
---------------------------------------------------------------
my-cookie-name     1         mydomain.com        /foo/bar/
my-cookie-name     value     mydomain.com        /
---------------------------------------------------------------

This inconsistency does not manifest consistently. Since this problem occurs infrequently, it is challenging to pinpoint. As a temporary solution, I remove the cookie before setting a new value and temporarily avoid encountering the issue again. However, I believe this approach is flawed.

The cookie named 'my-cookie-name' is specifically set in one section of the code. This discrepancy was identified on my development machine, ruling out the possibility of stale cookies being responsible.

I utilize cookies to toggle a state, as demonstrated by the following snippet:

var state = 'on';
$elem.on('click', function(e){
    state = state === 'on' ? 'off' : 'on';
    Cookies.set('my-cookie-name', state, {path: '/'});
});

Could this usage be incorrect? Should I consider removing old cookies before setting new values?

Browser: Chrome v45

The GitHub thread for this issue

Answer №1

A cookie is characterized by its domain, path, and secure attributes, so it's important to be cautious to prevent duplicates.

However, why does this issue occur? It's difficult to say for sure, but here is my hypothesis:

  1. Even if you only call it once, the user may already have a locally stored cookie. Modifying the code doesn't erase a previously persisted cookie.
  2. You might be passing an Object Literal reference in the attributes argument, then another piece of code modifies the Object later on, leading to the cookie being set with a different Path.
  3. The server may be setting another cookie with different attributes, causing a duplication when attempting to set it on the client side.
  4. There could be some code altering the behavior of Cookies methods dynamically, resulting in duplication when calling Cookies.set().

Aside from these possibilities, I can't think of any other reasons for this issue.

I suggest following this guide, which outlines how to simplify your code to isolate the problem.

We are planning to document duplicated cookies. The same link contains related discussions that may assist you in resolving the issue.

I hope this information proves helpful.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Rule for jQuery validation based on variables

I am facing an issue with validation of login asynchronously in my HTML form using the jQuery Validation Plugin. I would like to trigger a request for login validity on blur, and validate it upon receiving a response. Below is the code snippet: var login ...

What steps can be taken to safeguard data while navigating within the Angular framework?

I am facing an issue with storing an array of items in a service (referred to as cart service) and displaying it in the component (cart.component.ts). The components bgview.component.ts and single.component.ts are involved in selecting individual items, wi ...

Is there a way to make all Bootstrap column heights equal using only jQuery?

I am currently working on matching the heights of two columns without using an existing library like match-height.js. In this specific case, I have a row with 2 columns where the first column contains a centered black square and the second column contains ...

Issue with Type-Error when accessing theme using StyledComponents and TypeScript in Material-UI(React)

I attempted to access the theme within one of my styled components like this: const ToolbarPlaceholder = styled('div')((theme: any) => ({ minHeight: theme.mixins.toolbar.minHeight, })); This information was found in the documentation: htt ...

Creating dynamic content in the Ajax-enabled Smart Admin theme: A step-by-step guide

As I work on developing an application for a client, my focus is on creating a web service using Laravel5 for the backend. To enhance the user interface of this web service, I have chosen to incorporate the Smart Admin Theme, specifically utilizing the Aja ...

Is it possible to access the operating system's native emoji picker directly from a website?

While there are numerous javascript plugins and libraries available for allowing users to select emojis for text inputs, both Windows and Mac operating systems already have their own native emoji pickers accessible via ⊞ Win. or CTRL⌘Space. Is there a ...

How can I store the content of a meta tag in a JavaScript variable?

Similar Question: How can I extract data from a meta tag using JavaScript? I have a meta tag that can be customized with content on a specific page, and I'm looking to retrieve this content as a variable in JavaScript. ...

The `stream.Transform.unshift()` method in Node.js

Let's take a look at this simple example: stream = require 'stream' util = require 'util' class TestTransform extends stream.Transform _transform: (chunk, encoding, callback) -> if not @noMore @noMore ...

Modify the Div background color by accessing the HEX value saved in a JSON file

(I made a change to my code and removed the br tag from info2) Currently, I have successfully implemented a feature using jQuery that reads color names and hex values from a JSON file, populates them in a drop-down select menu (which is working fine). Now ...

Navigating using Backbone Marionette URL to Server Endpoint

I need to implement client-side validation to check if the user is logged in, and if not, redirect them to the sign-in page. The issue is that the sign-in page exists outside of my Backbone Marionette app. Is there a way in Marionette, Backbone, jQuery, or ...

Pseudo-element fails to display in React when applied to a paragraph tag, even with display block property set

I am experiencing an issue where the pseudo element ::after is not appearing in my browser. I am currently working with React.js and Material UI's makeStyles. Here is the code snippet causing the problem: modalTitle: { borderBottom: '2px sol ...

Updating Angular UI-Router to version 1.0 causes issues with resolving data inside views

After upgrading my Angular UI-Router to version 1.0, I came across an interesting statement in the migration guide: We no longer process resolve blocks that are declared inside a views While it makes sense to move all resolve blocks to the parent state ...

Creating a div that becomes fixed at the top of the page after scrolling down a certain distance is a great way to improve user experience on a

I am struggling to create a fixed navigation bar that sticks to the top of the page after scrolling 500px, but without using position: fixed. Despite trying various solutions, none seem to work due to the unique layout of my navigation bar. Strangely enoug ...

Encountered an error while running npm run dev on a NextJS application due to an

Upon running the npm run dev command, the next app is displaying an error message: $→mmoLD;%g?wŷ↓▬ovH0a5*ؒl͛Siy☺rO7%L]%∟hk ^ SyntaxError: Invalid or unexpected token at wrapSafe (internal/modules/cjs/loader.js:988:16) at Module._comp ...

Upgrade from Next.js version 12

Greetings to all! I have recently been assigned the task of migrating a project from next.js version 12 to the latest version. The changes in page routing and app routing are posing some challenges for me as I attempt to migrate the entire website. Is ther ...

Develop a custom class for importing pipes in Angular 4

Currently, I am working on creating a pipe that will replace specific keywords with the correct strings. To keep this pipe well-structured, I have decided to store my keywords and strings in another file. Below is the code snippet for reference: import { ...

Display the number of likes without having to refresh the page

On my website, there is a like/unlike post feature. When I click the like button, I want the value of check2 to appear next to the like button without needing to refresh the page. Currently, after clicking like, the data is inserted but only appears after ...

Setting the rotation position in JQuery prior to initiating the animation

Perhaps I could phrase my query differently as How can I rotate an image in JQuery from a starting position other than 0 degrees. I am attempting to animate the rotation of an image from -50deg to 0deg. However, regardless of what I do, JQuery seems to al ...

What is the best way to split up the information and place it into separate text boxes?

I am currently working on a page that allows users to create and edit email structures. To facilitate editing, I added two columns to the page. One of the columns displays information from all the email structures along with two buttons - one for editing ...

What is the method to render certain text as bold using a json string?

I need assistance with concatenating two strings in react while ensuring that the first string is displayed in bold, while the second one remains unchanged. The first string I want to emphasize is stored in a JSON file, and the second string comes from an ...