
Security News
CISA Kills Off RSS Feeds for KEVs and Cyber Alerts
CISA is discontinuing official RSS support for KEV and cybersecurity alerts, shifting updates to email and social media, disrupting automation workflows.
react-cookie
Advanced tools
The react-cookie package is a library for handling cookies in React applications. It provides hooks and components to easily set, get, and remove cookies, making it simple to manage user sessions and preferences.
Setting a Cookie
This feature allows you to set a cookie using the `useCookies` hook. In this example, a cookie named 'user' is set with the value 'John Doe' when the login button is clicked.
import { useCookies } from 'react-cookie';
function App() {
const [cookies, setCookie] = useCookies(['user']);
const handleLogin = () => {
setCookie('user', 'John Doe', { path: '/' });
};
return (
<div>
<button onClick={handleLogin}>Login</button>
</div>
);
}
Getting a Cookie
This feature allows you to get a cookie using the `useCookies` hook. In this example, the value of the 'user' cookie is displayed in a paragraph.
import { useCookies } from 'react-cookie';
function App() {
const [cookies] = useCookies(['user']);
return (
<div>
<p>User: {cookies.user}</p>
</div>
);
}
Removing a Cookie
This feature allows you to remove a cookie using the `useCookies` hook. In this example, the 'user' cookie is removed when the logout button is clicked.
import { useCookies } from 'react-cookie';
function App() {
const [cookies, setCookie, removeCookie] = useCookies(['user']);
const handleLogout = () => {
removeCookie('user', { path: '/' });
};
return (
<div>
<button onClick={handleLogout}>Logout</button>
</div>
);
}
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.
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.tsx
import React from 'react';
import App from './App';
import { CookiesProvider } from 'react-cookie';
export default function Root(): React.ReactElement {
return (
<CookiesProvider defaultSetOptions={{ path: '/' }}>
<App />
</CookiesProvider>
);
}
// App.tsx
import React from 'react';
import { useCookies } from 'react-cookie';
import NameForm from './NameForm';
interface CookieValues {
name?: string;
}
function App(): React.ReactElement {
const [cookies, setCookie] = useCookies<'name', CookieValues>(['name']);
function onChange(newName: string): void {
setCookie('name', newName);
}
return (
<div>
<NameForm name={cookies.name || ''} onChange={onChange} />
{cookies.name && <h1>Hello {cookies.name}!</h1>}
</div>
);
}
export default App;
// Root.tsx
import React from 'react';
import App from './App';
import { CookiesProvider } from 'react-cookie';
export default function Root(): React.ReactElement {
return (
<CookiesProvider>
<App />
</CookiesProvider>
);
}
// App.tsx
import React, { Component } from 'react';
import { withCookies, Cookies, ReactCookieProps } from 'react-cookie';
import NameForm from './NameForm';
interface State {
name: string;
}
interface Props extends ReactCookieProps {
cookies: Cookies;
}
class App extends Component<Props, State> {
constructor(props: Props) {
super(props);
const { cookies } = props;
this.state = {
name: cookies.get('name') || 'Ben',
};
}
handleNameChange(name: string): void {
const { cookies } = this.props;
cookies.set('name', name, { path: '/' });
this.setState({ name });
}
render(): React.ReactNode {
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.ts
import React from 'react';
import { useCookies } from 'react-cookie';
import NameForm from './NameForm';
function App() {
const [cookies, setCookie] = useCookies(['name']);
function onChange(newName: string) {
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.ts
import React from 'react';
import ReactDOMServer from 'react-dom/server';
import { CookiesProvider } from 'react-cookie';
import { Request, Response } from 'express';
import Html from './components/Html';
import App from './components/App';
export default function middleware(req: Request, res: Response) {
const markup = ReactDOMServer.renderToString(
<CookiesProvider cookies={req.universalCookies}>
<App />
</CookiesProvider>,
);
const html = ReactDOMServer.renderToStaticMarkup(<Html markup={markup} />);
res.send('<!DOCTYPE html>' + html);
}
// src/client.ts
import React from 'react';
import { createRoot } from 'react-dom/client';
import { CookiesProvider } from 'react-cookie';
import App from './components/App';
const root = createRoot(document.getElementById('main-app'));
root.render(
<CookiesProvider>
<App />
</CookiesProvider>,
);
// server.ts
import express from 'express';
import serverMiddleware from './src/server';
import cookiesMiddleware from 'universal-cookie-express';
const app = express();
app.use(cookiesMiddleware()).use(serverMiddleware);
app.listen(8080, function () {
console.log('Listening on 8080...');
});
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.
Security News
CISA is discontinuing official RSS support for KEV and cybersecurity alerts, shifting updates to email and social media, disrupting automation workflows.
Security News
The MCP community is launching an official registry to standardize AI tool discovery and let agents dynamically find and install MCP servers.
Research
Security News
Socket uncovers an npm Trojan stealing crypto wallets and BullX credentials via obfuscated code and Telegram exfiltration.