
Product
Introducing GitHub Actions Scanning Support
Detect malware, unsafe data flows, and license issues in GitHub Actions with Socket’s new workflow scanning support.
react-cookie
Advanced tools
Universal cookies for React
universal-cookie
- Universal cookies for JavaScriptuniversal-cookie-express
- Hook cookies get/set on Express for server-renderingnpm install react-cookie
or in the browser (global variable ReactCookie
):
<script
crossorigin
src="https://unpkg.com/react@16/umd/react.production.js"
></script>
<script
crossorigin
src="https://unpkg.com/universal-cookie@7/umd/universalCookie.min.js"
></script>
<script
crossorigin
src="https://unpkg.com/react-cookie@7/umd/reactCookie.min.js"
></script>
<CookiesProvider defaultSetOptions />
Set the user cookies
On the server, the cookies
props must be set using req.universalCookies
or new Cookie(cookieHeader)
useCookies([dependencies], [options])
Access and modify cookies using React hooks.
const [cookies, setCookie, removeCookie] = useCookies(['cookie-name']);
React hooks are available starting from React 16.8
dependencies
(optional)Let you optionally specify a list of cookie names your component depend on or that should trigger a re-render. If unspecified, it will render on every cookie change.
options
(optional)const [cookies, setCookie, removeCookie] = useCookies(['cookie-name'], {
doNotParse: true,
});
cookies
Javascript object with all your cookies. The key is the cookie name.
setCookie(name, value, [options])
Set a cookie value
/
as the path if you want your cookie to be accessible on all pagesremoveCookie(name, [options])
Remove a cookie
/
as the path if you want your cookie to be accessible on all pagesupdateCookies()
Read back the cookies from the browser and triggers the change listeners. This should normally not be necessary because this library detects cookie changes automatically.
withCookies(Component)
Give access to your cookies anywhere. Add the following props to your component:
Your original static properties will be hoisted on the returned component. You can also access the original component by using the WrappedComponent
static property. Example:
function MyComponent() {
return null;
}
const NewComponent = withCookies(MyComponent);
NewComponent.WrappedComponent === MyComponent;
get(name, [options])
Get a cookie value
getAll([options])
Get all cookies
set(name, value, [options])
Set a cookie value
/
as the path if you want your cookie to be accessible on all pagesremove(name, [options])
Remove a cookie
/
as the path if you want your cookie to be accessible on all pages// Root.jsx
import React from 'react';
import App from './App';
import { CookiesProvider } from 'react-cookie';
export default function Root() {
return (
<CookiesProvider defaultSetOptions={{ path: '/' }}>
<App />
</CookiesProvider>
);
}
// App.jsx
import React from 'react';
import { useCookies } from 'react-cookie';
import NameForm from './NameForm';
function App() {
const [cookies, setCookie] = useCookies(['name']);
function onChange(newName) {
setCookie('name', newName);
}
return (
<div>
<NameForm name={cookies.name} onChange={onChange} />
{cookies.name && <h1>Hello {cookies.name}!</h1>}
</div>
);
}
export default App;
// Root.jsx
import React from 'react';
import App from './App';
import { CookiesProvider } from 'react-cookie';
export default function Root() {
return (
<CookiesProvider>
<App />
</CookiesProvider>
);
}
// App.jsx
import React, { Component } from 'react';
import { instanceOf } from 'prop-types';
import { withCookies, Cookies } from 'react-cookie';
import NameForm from './NameForm';
class App extends Component {
static propTypes = {
cookies: instanceOf(Cookies).isRequired,
};
constructor(props) {
super(props);
const { cookies } = props;
this.state = {
name: cookies.get('name') || 'Ben',
};
}
handleNameChange(name) {
const { cookies } = this.props;
cookies.set('name', name, { path: '/' });
this.setState({ name });
}
render() {
const { name } = this.state;
return (
<div>
<NameForm name={name} onChange={this.handleNameChange.bind(this)} />
{this.state.name && <h1>Hello {this.state.name}!</h1>}
</div>
);
}
}
export default withCookies(App);
// src/components/App.js
import React from 'react';
import { useCookies } from 'react-cookie';
import NameForm from './NameForm';
function App() {
const [cookies, setCookie] = useCookies(['name']);
function onChange(newName) {
setCookie('name', newName, { path: '/' });
}
return (
<div>
<NameForm name={cookies.name} onChange={onChange} />
{cookies.name && <h1>Hello {cookies.name}!</h1>}
</div>
);
}
export default App;
// src/server.js
import React from 'react';
import ReactDOMServer from 'react-dom/server';
import { CookiesProvider } from 'react-cookie';
import Html from './components/Html';
import App from './components/App';
export default function middleware(req, res) {
const markup = ReactDOMServer.renderToString(
<CookiesProvider cookies={req.universalCookies}>
<App />
</CookiesProvider>,
);
const html = ReactDOMServer.renderToStaticMarkup(<Html markup={markup} />);
res.send('<!DOCTYPE html>' + html);
}
// src/client.js
import React from 'react';
import ReactDOM from 'react-dom';
import { CookiesProvider } from 'react-cookie';
import App from './components/App';
const appEl = document.getElementById('main-app');
ReactDOM.render(
<CookiesProvider>
<App />
</CookiesProvider>,
appEl,
);
// server.js
require('@babel/register');
const express = require('express');
const serverMiddleware = require('./src/server').default;
const cookiesMiddleware = require('universal-cookie-express');
const app = express();
app
.use('/assets', express.static('dist'))
.use(cookiesMiddleware())
.use(serverMiddleware);
app.listen(8080, function () {
console.log('Listening on 8080...');
});
js-cookie is a simple, lightweight JavaScript API for handling cookies. It is not specific to React but can be used in any JavaScript project. Compared to react-cookie, js-cookie requires more manual handling of cookies but offers more flexibility for non-React environments.
universal-cookie is a library for handling cookies in both client and server environments. It provides a consistent API for managing cookies in JavaScript and is often used in conjunction with server-side rendering frameworks. Compared to react-cookie, universal-cookie is more versatile for isomorphic applications.
react-use-cookie is a React hook for managing cookies. It is similar to react-cookie but offers a simpler API with fewer features. It is suitable for projects that need basic cookie management without the additional functionality provided by react-cookie.
FAQs
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Product
Detect malware, unsafe data flows, and license issues in GitHub Actions with Socket’s new workflow scanning support.
Product
Add real-time Socket webhook events to your workflows to automatically receive pull request scan results and security alerts in real time.
Research
The Socket Threat Research Team uncovered malicious NuGet packages typosquatting the popular Nethereum project to steal wallet keys.