React Auth Kit
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.
Common errors
-
Invariant Violation: You must wrap your application in an <AuthProvider>
cause Attempting to use `react-auth-kit` hooks (e.g., `useSignIn`, `useAuthUser`) or components (e.g., `RequireAuth`) outside of the `AuthProvider`'s context.fixEnsure your entire application or the parts that need authentication are wrapped within the `AuthProvider` component, initialized with a `store` created by `createStore`. -
Cannot find module 'react-auth-kit/PrivateRoute' or 'react-auth-kit/dist/PrivateRoute'
cause This error occurs after upgrading to `react-auth-kit` v3.x, where the `PrivateRoute` component was deprecated and moved/renamed.fixInstall 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';`. -
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'.cause Incorrect or incomplete parameters provided to the `signIn` function (returned by `useSignIn`), often missing required properties or providing properties with incorrect types.fixReview 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.
Warnings
- breaking 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`.
- gotcha 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.
- gotcha 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.
Install
-
npm install react-auth-kit -
yarn add react-auth-kit -
pnpm add react-auth-kit
Imports
- AuthProvider
const { AuthProvider } = require('react-auth-kit');import { AuthProvider } from 'react-auth-kit'; - createStore
import { createStore } from 'react-auth-kit'; - useSignIn
import useSignIn from 'react-auth-kit/useSignIn';
import { useSignIn } from 'react-auth-kit'; - RequireAuth
import { PrivateRoute } from 'react-auth-kit';import RequireAuth from '@auth-kit/react-router/RequireAuth';
Quickstart
import React from 'react';
import ReactDOM from 'react-dom/client';
import { AuthProvider, createStore, useSignIn, useSignOut, useIsAuthenticated, useAuthUser, useAuthHeader, useAuthToken } from 'react-auth-kit';
import { BrowserRouter, Routes, Route, useNavigate, Link } from 'react-router-dom';
import RequireAuth from '@auth-kit/react-router/RequireAuth';
// 1. Create the Auth Store
const store = createStore({
authName: '_auth',
authType: 'cookie',
cookieDomain: window.location.hostname,
cookieSecure: window.location.protocol === 'https:',
});
const LoginPage: React.FC = () => {
const signIn = useSignIn();
const navigate = useNavigate();
const login = () => {
// In a real app, you'd make an API call here to get the token
const token = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyLCJleHAiOjE3Mzk4MTc2MDB9'; // Example JWT
const refreshToken = 'refresh-token-example'; // Optional refresh token
const authState = { user: 'John Doe', role: 'admin' }; // Example user state
if (
signIn({
token: token,
expiresIn: 60 * 60, // 1 hour
tokenType: 'Bearer',
authState: authState,
refreshToken: refreshToken, // Optional
refreshTokenExpireIn: 10 * 60 * 60 // 10 hours for refresh token
})
) {
navigate('/dashboard');
} else {
alert('Login failed!');
}
};
return (
<div>
<h1>Login Page</h1>
<button onClick={login}>Simulate Login</button>
<p><Link to="/">Go to Home</Link></p>
</div>
);
};
const DashboardPage: React.FC = () => {
const signOut = useSignOut();
const isAuthenticated = useIsAuthenticated();
const auth = useAuthUser();
const authHeader = useAuthHeader();
const authToken = useAuthToken();
const navigate = useNavigate();
const logout = () => {
signOut();
navigate('/');
};
return (
<div>
<h1>Dashboard Page</h1>
{isAuthenticated() ? (
<>
<p>Welcome, {auth()?.user}!</p>
<p>Your role: {auth()?.role}</p>
<p>Auth Header: {authHeader()}</p>
<p>Auth Token: {authToken()}</p>
<button onClick={logout}>Logout</button>
</>
) : (
<p>You are not authenticated.</p>
)}
<p><Link to="/">Go to Home</Link></p>
</div>
);
};
const HomePage: React.FC = () => (
<div>
<h1>Home Page</h1>
<p>This page is public.</p>
<p><Link to="/dashboard">Go to Dashboard</Link></p>
<p><Link to="/login">Go to Login</Link></p>
</div>
);
const App: React.FC = () => {
return (
<BrowserRouter>
<AuthProvider store={store}>
<Routes>
<Route path="/" element={<HomePage />} />
<Route path="/login" element={<LoginPage />} />
<Route
path="/dashboard"
element={
<RequireAuth fallbackPath="/login">
<DashboardPage />
</RequireAuth>
}
/>
</Routes>
</AuthProvider>
</BrowserRouter>
);
};
const root = ReactDOM.createRoot(document.getElementById('root') as HTMLElement);
root.render(
<React.StrictMode>
<App />
</React.StrictMode>
);