{"id":16668,"library":"react-auth-kit","title":"React Auth Kit","description":"React Auth Kit is a robust and flexible authentication library for React applications, designed to simplify token-based authentication flows, particularly with JWTs. The current stable release series is `v3.x`, with `v3.1.3` being the latest stable patch, while `v4.0.2-alpha.11` is an active alpha development branch. The library is actively maintained with a regular release cadence, including frequent patch updates and minor feature additions, as well as significant major releases (like `v3.0.0`) that introduce architectural changes. Key differentiators include its adoption of an RxJS-based token store for enhanced performance and reactive state management since version 3.0.0, a monorepo structure allowing for extensible and modular packages, and dedicated integrations like `@auth-kit/react-router` for seamless protected routing and `@auth-kit/next` for Next.js support (introduced in v3.1.0). It fully supports TypeScript, providing type definitions out-of-the-box.","status":"active","version":"4.0.2-alpha.11","language":"javascript","source_language":"en","source_url":"https://github.com/react-auth-kit/react-auth-kit","tags":["javascript","react","auth","authentication","jwt","jsonwebtoken","token","typescript"],"install":[{"cmd":"npm install react-auth-kit","lang":"bash","label":"npm"},{"cmd":"yarn add react-auth-kit","lang":"bash","label":"yarn"},{"cmd":"pnpm add react-auth-kit","lang":"bash","label":"pnpm"}],"dependencies":[{"reason":"Peer dependency for all React Auth Kit packages.","package":"react","optional":false},{"reason":"Required for the `@auth-kit/react-router` package's `RequireAuth` component and related utilities.","package":"react-router-dom","optional":true}],"imports":[{"note":"The primary context provider for the authentication state. Named import, not default.","wrong":"const { AuthProvider } = require('react-auth-kit');","symbol":"AuthProvider","correct":"import { AuthProvider } from 'react-auth-kit';"},{"note":"Function to initialize the authentication store. Must be called once to configure `AuthProvider`.","wrong":null,"symbol":"createStore","correct":"import { createStore } from 'react-auth-kit';"},{"note":"One of the core hooks for managing authentication state; all hooks are named imports from the main package.","wrong":"import useSignIn from 'react-auth-kit/useSignIn';","symbol":"useSignIn","correct":"import { useSignIn } from 'react-auth-kit';"},{"note":"Since `v3.0.0`, the route protection component moved to a separate sub-package and was renamed from `PrivateRoute` to `RequireAuth`. It's a default export from its specific module path.","wrong":"import { PrivateRoute } from 'react-auth-kit';","symbol":"RequireAuth","correct":"import RequireAuth from '@auth-kit/react-router/RequireAuth';"}],"quickstart":{"code":"import React from 'react';\nimport ReactDOM from 'react-dom/client';\nimport { AuthProvider, createStore, useSignIn, useSignOut, useIsAuthenticated, useAuthUser, useAuthHeader, useAuthToken } from 'react-auth-kit';\nimport { BrowserRouter, Routes, Route, useNavigate, Link } from 'react-router-dom';\nimport RequireAuth from '@auth-kit/react-router/RequireAuth';\n\n// 1. Create the Auth Store\nconst store = createStore({\n  authName: '_auth',\n  authType: 'cookie',\n  cookieDomain: window.location.hostname,\n  cookieSecure: window.location.protocol === 'https:',\n});\n\nconst LoginPage: React.FC = () => {\n  const signIn = useSignIn();\n  const navigate = useNavigate();\n\n  const login = () => {\n    // In a real app, you'd make an API call here to get the token\n    const token = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyLCJleHAiOjE3Mzk4MTc2MDB9'; // Example JWT\n    const refreshToken = 'refresh-token-example'; // Optional refresh token\n    const authState = { user: 'John Doe', role: 'admin' }; // Example user state\n\n    if (\n      signIn({\n        token: token,\n        expiresIn: 60 * 60, // 1 hour\n        tokenType: 'Bearer',\n        authState: authState,\n        refreshToken: refreshToken, // Optional\n        refreshTokenExpireIn: 10 * 60 * 60 // 10 hours for refresh token\n      })\n    ) {\n      navigate('/dashboard');\n    } else {\n      alert('Login failed!');\n    }\n  };\n\n  return (\n    <div>\n      <h1>Login Page</h1>\n      <button onClick={login}>Simulate Login</button>\n      <p><Link to=\"/\">Go to Home</Link></p>\n    </div>\n  );\n};\n\nconst DashboardPage: React.FC = () => {\n  const signOut = useSignOut();\n  const isAuthenticated = useIsAuthenticated();\n  const auth = useAuthUser();\n  const authHeader = useAuthHeader();\n  const authToken = useAuthToken();\n  const navigate = useNavigate();\n\n  const logout = () => {\n    signOut();\n    navigate('/');\n  };\n\n  return (\n    <div>\n      <h1>Dashboard Page</h1>\n      {isAuthenticated() ? (\n        <>\n          <p>Welcome, {auth()?.user}!</p>\n          <p>Your role: {auth()?.role}</p>\n          <p>Auth Header: {authHeader()}</p>\n          <p>Auth Token: {authToken()}</p>\n          <button onClick={logout}>Logout</button>\n        </>\n      ) : (\n        <p>You are not authenticated.</p>\n      )}\n      <p><Link to=\"/\">Go to Home</Link></p>\n    </div>\n  );\n};\n\nconst HomePage: React.FC = () => (\n  <div>\n    <h1>Home Page</h1>\n    <p>This page is public.</p>\n    <p><Link to=\"/dashboard\">Go to Dashboard</Link></p>\n    <p><Link to=\"/login\">Go to Login</Link></p>\n  </div>\n);\n\nconst App: React.FC = () => {\n  return (\n    <BrowserRouter>\n      <AuthProvider store={store}>\n        <Routes>\n          <Route path=\"/\" element={<HomePage />} />\n          <Route path=\"/login\" element={<LoginPage />} />\n          <Route\n            path=\"/dashboard\"\n            element={\n              <RequireAuth fallbackPath=\"/login\">\n                <DashboardPage />\n              </RequireAuth>\n            }\n          />\n        </Routes>\n      </AuthProvider>\n    </BrowserRouter>\n  );\n};\n\nconst root = ReactDOM.createRoot(document.getElementById('root') as HTMLElement);\nroot.render(\n  <React.StrictMode>\n    <App />\n  </React.StrictMode>\n);","lang":"typescript","description":"This quickstart demonstrates a complete React application using `react-auth-kit` for token-based authentication, featuring login, logout, protected routes, and displaying user information."},"warnings":[{"fix":"For route protection, install `@auth-kit/react-router` (`npm i @auth-kit/react-router`) and import `RequireAuth` as `import RequireAuth from '@auth-kit/react-router/RequireAuth';`. Update any custom logic relying on direct store manipulation to align with the RxJS-based architecture.","message":"Version `3.0.0` introduced significant breaking changes. The internal token store was rewritten to use RxJS, which might affect advanced customizations. More importantly, the `PrivateRoute` component was moved to a separate package (`@auth-kit/react-router`) and renamed to `RequireAuth`.","severity":"breaking","affected_versions":">=3.0.0"},{"fix":"Always set `cookieDomain` to `window.location.hostname` or your specific domain, and `cookieSecure` to `window.location.protocol === 'https:'` to match your deployment environment. Refer to the documentation for advanced cookie configuration.","message":"When configuring the authentication store using `createStore`, ensure `cookieDomain` and `cookieSecure` parameters are correctly set, especially in production environments. Incorrect values can lead to cookies not being set or retrieved, causing authentication failures.","severity":"gotcha","affected_versions":">=3.1.1"},{"fix":"Always use ES Modules `import` syntax for all `react-auth-kit` packages and their exports. Ensure your project's `tsconfig.json` (for TypeScript) and `package.json` (for Node.js/bundlers) are configured for modern module resolution (e.g., `\"type\": \"module\"` in `package.json`).","message":"While `react-auth-kit` supports modern JavaScript environments, it is primarily designed for ESM (ECMAScript Modules) consumption. Using CommonJS `require()` statements might lead to issues or require specific bundler configurations, especially for sub-packages.","severity":"gotcha","affected_versions":">=3.0.0"}],"env_vars":null,"last_verified":"2026-04-22T00:00:00.000Z","next_check":"2026-07-21T00:00:00.000Z","problems":[{"fix":"Ensure your entire application or the parts that need authentication are wrapped within the `AuthProvider` component, initialized with a `store` created by `createStore`.","cause":"Attempting to use `react-auth-kit` hooks (e.g., `useSignIn`, `useAuthUser`) or components (e.g., `RequireAuth`) outside of the `AuthProvider`'s context.","error":"Invariant Violation: You must wrap your application in an <AuthProvider>"},{"fix":"Install the `@auth-kit/react-router` package (`npm i @auth-kit/react-router`) and replace `PrivateRoute` with `RequireAuth`, importing it as `import RequireAuth from '@auth-kit/react-router/RequireAuth';`.","cause":"This error occurs after upgrading to `react-auth-kit` v3.x, where the `PrivateRoute` component was deprecated and moved/renamed.","error":"Cannot find module 'react-auth-kit/PrivateRoute' or 'react-auth-kit/dist/PrivateRoute'"},{"fix":"Review the `SignInFunctionParams` interface from `react-auth-kit`'s TypeScript definitions and ensure all required fields (`token`, `expiresIn`, `tokenType`) are present and correctly typed. Also, verify `authState` and `refreshToken` properties if used.","cause":"Incorrect or incomplete parameters provided to the `signIn` function (returned by `useSignIn`), often missing required properties or providing properties with incorrect types.","error":"Argument of type '{ token: string; expiresIn: number; tokenType: string; authState: { user: string; role: string; }; refreshToken: string; refreshTokenExpireIn: number; }' is not assignable to parameter of type 'SignInFunctionParams'."}],"ecosystem":"npm"}