Load and save cookies within your React application

Related tags

Storage cookies
Overview
Comments
  • reactCookie.remove not functioning.

    reactCookie.remove not functioning.

    I can't believe this is actually a problem with the library, but is there some condition in my application that could be causing behavior like what I'm observing in this console screenshot?

    https://www.dropbox.com/s/805pyfznabpyr54/Screenshot%202016-02-02%2012.57.18.png?dl=0

    Other pages in the application appear to be working as expected.

    opened by jcdavison 27
  • Missing the cookie header or object

    Missing the cookie header or object

    I am using universal-cookie and am experiencing this problem when instantiating it. I'm doing the same thing as the example:

    import Cookies from 'universal-cookie';
    const cookies = new Cookies();
    
    opened by davidsonsns 26
  • Using mixed imports brakes when using native ESmodules.

    Using mixed imports brakes when using native ESmodules.

    https://github.com/reactivestack/cookies/blob/a97969a9755f2a7fc5977a448a97f0fd39ac3a3c/packages/universal-cookie/src/Cookies.ts#L14

    When trying to consume this package with rollup and <script type="module" /> having mixed imports means that require is not defined.

    opened by chmelevskij 11
  • react-cookie 3.08 error: cookies.getAll is not a function

    react-cookie 3.08 error: cookies.getAll is not a function

    Currently have react version 16.7.0, just updated react-cookies to 3.0.8. After updating and restarting client, getting above error and UI doesn't load. Screenshot attached. Thank you

    screen shot 2019-01-30 at 10 29 59 am
    opened by jalutz 11
  • Cannot work server-side!

    Cannot work server-side!

    Hi,

    with this code:

    var express = require('express');
    var router = express.Router();
    var reactCookie = require('react-cookie');
    
    router.get('/', function(req, res) {
        reactCookie.plugToRequest(req, res);
    
        someFuncWithCallback( function() {
            var cookie = reactCookie.load("somecookie");
        });
    });
    

    If two people request this route at the same time and the callback gets called first for the 1st user, the cookie will be the cookie of the second user.

    Because you store the rawCookies globally in your script, instead of using a different rawCookies for each request, the first request will call plugToRequest() that will write rawCookies, and the second request will overwrite it... and by the time node.js has reached cookie.load(), it will return the second cookie to the first user, or viceversa...

    opened by maxgalbu 11
  • How do I read cookies on server?

    How do I read cookies on server?

    How do I read cookies on server?

    I save cookie in action creator:

    cookie.save('userId', userId);

    How do I load it on server? I know that I can access cookies in req.cookies but I want to keep the logic in the right place. I do not want to edit server.js file. When I do console.log(cookie.load('userId') I get undefined in server console.

    opened by developer239 11
  • cookie.parse did not to be executed

    cookie.parse did not to be executed

    hi I upgrade to the latest version[1.0.1] but there's something problem. I didn't see what's difference between the older version, but I saw IS_NODE always true both in browser or node environment. It might be the problem why cookie.parse wasn't executed.

    https://github.com/thereactivestack/react-cookie/blob/master/src/cookie.js#L13

    opened by blackbing 10
  • Using in jest tests

    Using in jest tests

    Hi,

    I would like to know out to use it in jest environment once I'm getting this error:

    Cannot read property 'cookie' of undefined at Cookies._updateBrowserValues (/home/bla/app/node_modules/universal-cookie/lib/Cookies.js:47:55)

    I tried to set the cookie in the test like this, before calling the usage in app, but it didn't work:

    import Cookies from 'universal-cookie'
    const cookieHandler = new Cookies()
    cookieHandler.set('foo', {}, { path: '/' });
    

    Thanks

    opened by taviroquai 9
  • Remove Cookie not working properly

    Remove Cookie not working properly

    const [cookies, setCookie, removeCookie] = useCookies();
    
    setCookie('key', value, {
              path: '/',
              maxAge: 86400 * 365,
            });
    
    removeCookie('key');
    

    Sometime cookie does not removing

    opened by krishnaTORQUE 8
  • react-cookie useCookies does not refresh in parents

    react-cookie useCookies does not refresh in parents

    Description

    The useCookies hook appears to be stateful rather than updating the global context. Is that intentional?

    Example

    // This function component never updates
    function Parent() {
      const [cookies, setCookie, removeCookie] = useCookies(['test']);
    
      if (cookie.test === 'test') {
        return <Child2 />;
      } else {
        return <Child />;
      }
    }
    
    function Child() {
      const [cookies, setCookie, removeCookie] = useCookies(['test']);
    
      useEffect(() => {
        setCookie('test', 'test', { path: '/' });
      });
    
      return null;
    }
    
    
    opened by generalpiston 8
  • CookieProvider not re-rendering component with jest and react-testing-library

    CookieProvider not re-rendering component with jest and react-testing-library

    I implemented one of those GDPR cookie banners. When you click a button it dismisses the banner and sets a cookie so we know not to show it again.

    Here’s the code (I’ve simplified it a bit for clarity):

    const CookieConsent = () => {
      const [cookies, setCookie] = useCookies([storageKey])
      const value = typeof cookies[storageKey] === "undefined" ? null : cookies[storageKey]
      const dismissed = JSON.parse(value)
    
      const dismiss = () => {
        setCookie(storageKey, true)
      }
    
      if (dismissed) {
        return null
      }
    
      return <>
        <Message>{text}</Message>
    
        <Button onClick={dismiss}>OK</Button>
      </>
    }
    

    This all works when testing manually, but for some reason it doesn’t seem to work when I write an automated test for it.

    test("hidden after being dismissed", () => {
      let { queryByText, getByText } = render(
        <CookiesProvider>
          <CookieConsent />
        </CookiesProvider>
      )
    
      fireEvent.click(getByText("OK"))
    
      expect(queryByText(text)).not.toBeInTheDocument()
    })
    

    As best I can tell, when setCookie is called in the click handler, it’s not re-rendering the component.

    Is there something I’m doing wrong or is this a bug?

    opened by brandonweiss 8
  • Uncaught TypeError: cookies.get is not a function

    Uncaught TypeError: cookies.get is not a function

    Im trying to set up a darkmode cookie but i cant seem to get it working without problems

    Im sharing this because I believe that there are possibly others with the same problem.

    Im getting an Uncaught TypeError: cookies.get is not a function

    im using react-cookie 4.1.1

    import "./Settings.css"
    import { Link } from "react-router-dom"
    import { Box, FormControlLabel, Switch } from "@mui/material"
    import React, { useEffect, useState } from "react"
    import { useCookies } from "react-cookie";
    
    
    export function Settings(){
    
       
    
    const[cookies, setCookie, removeCookie] = useCookies(["darkmodeCookie"])
    
    setCookie("darkmodeCookie", false)
    
    function handleChange(){}
    
    let getVal = cookies.get("darkmodeCookie");
    
        return(
    
    
    
    <div>
    
         <h1>Settings</h1>
    
            
    
        <ul>
            
        <h1>{getVal}</h1>
            <h3>Ansicht</h3>
            <li><Box><FormControlLabel label="darkmode" control={<Switch onChange={handleChange} checked={true}/>}/></Box></li>
            <h3>Privatsphäre</h3>
            <li>test  <Link to="/settings/cookies" ><p className="moreInfoLink">mehr Erfahren</p></Link></li>
        </ul>
        
    
        </div>
    
            )
        }
    

    End of Settings.js

    import {withCookies} from "react-cookie"
    
    
    
    function App() {
    
      
    function CookiePopUp(){ // use after the render of the app return, useEffect not working try: componentDidMount
      
        const [cookieConsent, setConsentCookie] = useState(Cookies.get('cookieConsent') || 'undetermined');
      
        const handleAccept = () => {
          Cookies.set("consentCookie", "accepted", { expires: 365 });
          setConsentCookie("accepted");
        }
      
        if (cookieConsent === 'accepted') {
          return null;
        }else{
          return (
          <div className="PopUpConsentCookie">
            <p>Diese Website nutzt Cookies um die Benutzererfahrung zu verbessern</p>
            <button onClick={handleAccept}>Accept</button>
          </div>);
          }
    }  
    
    let persID = JSON.parse(localStorage.getItem("currentUser")); 
    
    // https://www.youtube.com/watch?v=vYL2wfmF3OQ für die menü leiste menu icon benutzen
    
      return (
    
        <>
        <Routes>
          <Route path="/settings" element={<Settings />} />
        </Routes>
        </>
      )
    }
    export default withCookies(App);
    

    End of App.js

    index.js

    import React from 'react';
    import ReactDOM from 'react-dom/client';
    import App from './App';
    import { CookiesProvider } from 'react-cookie';
    
    
    import { BrowserRouter } from 'react-router-dom';
    
    
    const root = ReactDOM.createRoot(document.getElementById('root'));
    root.render(
      <React.StrictMode>
        <BrowserRouter>
        <CookiesProvider>
        <App />
        </CookiesProvider>
        </BrowserRouter>
      </React.StrictMode>
    );
    
    

    Thank you for any help, and im sorry for any incovinience if the issue is caused by a mistake i made

    opened by Gollasso 0
  • Redundant Promise usage

    Redundant Promise usage

    Promise callback actually has no effect because it has been executing in-place synchronously. https://github.com/reactivestack/cookies/blob/4d12ae55e91a04d958b9c17f94ba152c951730a3/packages/universal-cookie/src/Cookies.ts#L21-L23 If it intended to be executed asynchronously, it should be rewritten like

     Promise.resolve().then(() => {
       this.HAS_DOCUMENT_COOKIE = hasDocumentCookie();
     });
    

    or unwrapped at all.

    opened by integrer 0
  • Access token cookie is not replaced!

    Access token cookie is not replaced!

    Hello,

    I have a problem:

    const cookies = new Cookies();

    1. I set initial cookie like this: cookies.set("accessToken", initialAccessToken, { secure: true, });
    2. After generating a new access token I use the same: cookies.set("accessToken", newAccessToken, { secure: true, });

    The problem is: it duplicates. I can see 2 cookies "accessToken". What do I do wrong? Thank you in advance.

    opened by sb-andy 0
  • access_token does not list in the cookie

    access_token does not list in the cookie

    I am getting the cookie by

    const ACCESS_TOKEN = 'access_token' as string;
    
    function AppRouter(): JSX.Element {
      const [cookie, setCookie] = useCookies([ACCESS_TOKEN]);
    
      useEffect(() => {
        console.log(cookie);
      }, [cookie]);
    

    From the applications tab we can see the access_token image But looks like it is not appeared when I use react-cookie image

    Is it a bug?

    opened by hhpr98 0
  • Update dependency express to v4.17.3 [SECURITY]

    Update dependency express to v4.17.3 [SECURITY]

    Mend Renovate

    This PR contains the following updates:

    | Package | Change | Age | Adoption | Passing | Confidence | |---|---|---|---|---|---| | express (source) | 4.17.2 -> 4.17.3 | age | adoption | passing | confidence |

    GitHub Vulnerability Alerts

    CVE-2022-24999

    qs before 6.10.3, as used in Express before 4.17.3 and other products, allows attackers to cause a Node process hang for an Express application because an __ proto__ key can be used. In many typical Express use cases, an unauthenticated remote attacker can place the attack payload in the query string of the URL that is used to visit the application, such as a[proto]=b&a[proto]&a[length]=100000000. The fix was backported to qs 6.9.7, 6.8.3, 6.7.3, 6.6.1, 6.5.3, 6.4.1, 6.3.3, and 6.2.4 (and therefore Express 4.17.3, which has "deps: [email protected]" in its release description, is not vulnerable).


    Release Notes

    expressjs/express

    v4.17.3

    Compare Source

    ===================


    Configuration

    📅 Schedule: Branch creation - "" (UTC), Automerge - At any time (no schedule defined).

    🚦 Automerge: Disabled by config. Please merge this manually once you are satisfied.

    Rebasing: Whenever PR becomes conflicted, or you tick the rebase/retry checkbox.

    🔕 Ignore: Close this PR and you won't be reminded about this update again.


    • [ ] If you want to rebase/retry this PR, check this box

    This PR has been generated by Mend Renovate. View repository job log here.

    opened by renovate[bot] 0
  • `universal-cookie` path param does not add cookie if page navigated to via client side nav

    `universal-cookie` path param does not add cookie if page navigated to via client side nav

    What's up

    Hey all, we are seeing the cookie not properly added to the browser if you redirect to the path via client side navigation.

    Example: cookie params

    {
        domain: CONFIG.cookieDomain,
        expires: null, 
        path: `/super-secret-page`, 
        sameSite: 'lax',
        secure: true, 
    }
    

    Repro:

    • Land on /regular-page, set a cookie on click of a button with path: '/'
    • client side navigate to /super-secret-page
    • set another cookie on click of a button with path set as above
    • open cookies in dev tools

    Expected:

    • the new cookie would appear

    Actual:

    • the new cookie isn't there

    Questions

    Is this behavior by design? If so, would you provide more information around how path is compared?

    opened by cmugla 0
Releases(v4.0.4)
Owner
Reactive Stack
Reactive Stack
A simple, lightweight JavaScript API for handling browser cookies

JavaScript Cookie A simple, lightweight JavaScript API for handling cookies Works in all browsers Accepts any character Heavily tested No dependency S

null 20.2k Jan 3, 2023
sessionStorage API which gracefully degrades to window.name & cookies when not available

sessionstorage The sessionStorage API is amazing and super useful when you need to store data temporarily in the browser. We used to abuse cookies for

null 22 Jul 25, 2022
Lightweight Angular module for access to cookies

angular-cookie Lightweight Angular module for access to cookies Installation You can install angular-cookie via bower bower install angular-cookie Ot

Ivan Pusic 269 Oct 5, 2022
A Vue.js plugin for manipulating cookies

vue-cookie A Vue.js plugin for manipulating cookies tested up to Vue v2.0.5 Installation Install through npm npm install vue-cookie --save Include in

Alf 819 Dec 8, 2022
local storage wrapper for both react-native and browser. Support size controlling, auto expiring, remote data auto syncing and getting batch data in one query.

react-native-storage This is a local storage wrapper for both react native apps (using AsyncStorage) and web apps (using localStorage). ES6 syntax, pr

Sunny Luo 2.9k Dec 16, 2022
React Firebase Material-UI insta reels app

React Firebase Material-UI insta reels app Website link : here P.S :- Open the website in laptop or desktop browsers This website is made for my learn

Jaydip Dey 8 Feb 11, 2022
Store your data in the world's fastest and most secure storage, powered by the blockchain technology⚡️

Store your data in the world's fastest and most secure storage, powered by the blockchain technology.

BlockDB 3 Mar 5, 2022
Browser storage interface for IndexedDB, WebSQL, LocalStorage, and in memory data with Schema and data validator.

Client Web Storage Browser storage interface for IndexedDB, WebSQL, LocalStorage, and in memory data with basic Schema and data validation. Installati

Before Semicolon 19 Sep 30, 2022
A script and resource loader for caching & loading files with localStorage

Basket.js is a script and resource loader for caching and loading scripts using localStorage ##Introduction for the Non-Developer Modern web applicati

Addy Osmani 3.4k Dec 30, 2022
localStorage and sessionStorage done right for AngularJS.

ngStorage An AngularJS module that makes Web Storage working in the Angular Way. Contains two services: $localStorage and $sessionStorage. Differences

G. Kay Lee 2.3k Nov 26, 2022
:lock: Secure localStorage data with high level of encryption and data compression

secure-ls Secure localStorage data with high level of encryption and data compression. LIVE DEMO Features Secure data with various types of encryption

Varun Malhotra 602 Nov 30, 2022
A enhanced web storage with env support, expire time control, change callback and LRU storage clear strategy.

enhanced-web-storage A enhanced web storage with env support, expire time control, change callback and LRU storage clear strategy. How to Start import

Ziwen Mei 15 Sep 10, 2021
The perfect combination: local business shopping and crypto.

The perfect combination: local business shopping and crypto. Get passive income and support local businesses.

Mauricio Figueiredo 4 Mar 19, 2022
A javascript based module to access and perform operations on Linode object storage via code.

Linode Object Storage JS Module A javascript based module to access and perform operations on Linode object storage via code. Code Guardian Installing

Core.ai 3 Jan 11, 2022
Expirable data storage based on localStorage and sessionStorage.

Expirable storage About The Project Expirable data storage based on localStorage and sessionStorage. Getting Started To get a local copy up and runnin

Wayfair Tech – Incubator 5 Oct 31, 2022
On this page, you can save and load all the awesome books you have and save the name and the author into the local storage. this project uses Javascript to interact with the pages

Awesome Books: refactor to use JavaScript classes In this project, We add the links to the applications into the final project Getting Started if you

Cesar Valencia 8 Nov 29, 2022
A simple To Do List application that allows users to save, edit, mark completed, and delete their to-dos, and save their list when application is closed. Build with JavaScript.

To Do List A simple To Do List online application that allows users to save, and manipulate their to-dos, and save their list when application is clos

Mahmoud Rizk 10 Dec 20, 2022
View maps, graphs, and tables of your save and compete in a casual, evergreen leaderboard of EU4 achievement speed runs. Upload and share your save with the world.

PDX Tools PDX Tools is a modern EU4 save file analyzer that allow users to view maps, graphs, and data tables of their save all within the browser. If

PDX Tools 24 Dec 27, 2022
Simple-load-more - This jQuery function will add a functionality to load 5 (or custom) more items. No AJAX functionality.

Simple Load More This jQuery plugin will add a functionality to load 5 (or custom) more items. Best for lists that are long and you want to hide all e

Zeshan Ahmed 28 Jan 4, 2023
implements user authentication and session management using Express.js, MongoDB, and secure cookies

Auth-Flow This project is a simple user authentication system that uses Express.js and MongoDB to store user data. The system allows users to sign up

Abdelrahman Ali 4 Mar 17, 2023