{"id":16672,"library":"redux-token-auth","title":"Redux Token Auth","description":"Redux Token Auth is a specialized JavaScript library designed to facilitate client-side authentication for React and Redux applications integrating with Rails backends that utilize Devise Token Auth. Currently at version 0.19.0, it provides a comprehensive set of Redux Thunk actions for core authentication flows, including user registration, sign-in, sign-out, and token verification, alongside a dedicated Redux reducer to manage the authentication state. It also offers a higher-order component for safeguarding application routes, requiring `react-router v4.0.0+` for proper functionality. The library mandates the presence of `redux-thunk` middleware and manages user credentials by leveraging `localStorage` in browser environments, with `AsyncStorage` support for React Native applications planned for future releases. Its primary differentiator lies in its tailored API and conventions that align directly with the Devise Token Auth ecosystem.","status":"active","version":"0.19.0","language":"javascript","source_language":"en","source_url":"https://github.com/kylecorbelli/redux-token-auth","tags":["javascript","react","redux","auth","authentication","token","devise","oauth","typescript"],"install":[{"cmd":"npm install redux-token-auth","lang":"bash","label":"npm"},{"cmd":"yarn add redux-token-auth","lang":"bash","label":"yarn"},{"cmd":"pnpm add redux-token-auth","lang":"bash","label":"pnpm"}],"dependencies":[{"reason":"Required for all asynchronous Redux Thunk actions (registerUser, signInUser, signOutUser, verifyToken, verifyCredentials) to function correctly.","package":"redux-thunk","optional":false},{"reason":"Required (v4.0.0+) for the `generateRequireSignInWrapper` higher-order component to provide protected routing functionality.","package":"react-router","optional":true}],"imports":[{"note":"This library is primarily designed for ESM consumption, shipping TypeScript types. Avoid CommonJS `require` syntax for optimal tooling.","wrong":"const { reduxTokenAuthReducer } = require('redux-token-auth');","symbol":"reduxTokenAuthReducer","correct":"import { reduxTokenAuthReducer } from 'redux-token-auth';"},{"note":"This function is a factory that takes a configuration object and returns a set of bound Redux Thunk actions and helper functions. It's a key entry point for using the library.","wrong":"const generateAuthActions = require('redux-token-auth').generateAuthActions;","symbol":"generateAuthActions","correct":"import { generateAuthActions } from 'redux-token-auth';"},{"note":"This higher-order component factory requires `react-router v4.0.0+` and should be used within a React application to protect routes. It's a named export, not a default export or a separate path.","wrong":"import generateRequireSignInWrapper from 'redux-token-auth/generateRequireSignInWrapper';","symbol":"generateRequireSignInWrapper","correct":"import { generateRequireSignInWrapper } from 'redux-token-auth';"}],"quickstart":{"code":"import { createStore, combineReducers, applyMiddleware } from 'redux';\nimport { thunk } from 'redux-thunk'; // Standard ESM import for redux-thunk\nimport { reduxTokenAuthReducer, generateAuthActions } from 'redux-token-auth';\n\n// 1. Redux Store Setup\nconst rootReducer = combineReducers({\n  reduxTokenAuth: reduxTokenAuthReducer,\n  // ... potentially other reducers\n});\n\n// Define a minimal initial state structure matching redux-token-auth's expectations\nconst initialState = {\n  reduxTokenAuth: {\n    currentUser: {\n      isLoading: false,\n      isSignedIn: false,\n      attributes: {}, // Example: firstName: null\n    },\n  },\n  // ... any other initial state needed by other reducers\n};\n\n// Create the Redux store\n// Note: In a modern React/Redux app, you'd typically use configureStore from @reduxjs/toolkit\nconst store = createStore(rootReducer, initialState as any, applyMiddleware(thunk));\n\n// 2. Configure redux-token-auth and generate actions\nconst config = {\n  apiBase: 'https://api.example.com/v1', // IMPORTANT: Replace with your actual Devise Token Auth API base URL\n  signOutPath: '/auth/sign_out',\n  signInPath: '/auth/sign_in',\n  signUpPath: '/auth',\n  userAttributes: {\n    firstName: 'first_name',\n    lastName: 'last_name',\n    email: 'email',\n  },\n  storage: typeof window !== 'undefined' ? localStorage : null, // Use localStorage in browser, null otherwise\n  // You can also add authProviderPaths, etc., as needed\n};\n\n// Generate the auth actions and the verifyCredentials helper\nconst {\n  registerUser,\n  signInUser,\n  signOutUser,\n  verifyToken,\n  verifyCredentials,\n} = generateAuthActions(config);\n\nconsole.log('Redux Store initialized and auth actions generated.');\n\n// 3. Dispatch verifyCredentials on application load\n// This ensures the app checks for existing user tokens on startup\nif (config.storage) { // Only attempt if localStorage is available (i.e., not server-side rendering)\n    store.dispatch(verifyCredentials() as any);\n    console.log('Dispatched verifyCredentials on app startup.');\n}\n\n// Example: Simulate a sign-in attempt (in a real app, this would be triggered by a user action)\nasync function simulateSignIn() {\n  console.log('\\n--- Simulating User Sign-In ---');\n  try {\n    const signInPayload = { email: 'user@example.com', password: 'password123' };\n    // Dispatch the signInUser thunk action\n    // Note: Type assertion `as any` is used here for simplicity in quickstart,\n    // in a real app, proper ThunkAction types would be used.\n    await store.dispatch(signInUser(signInPayload) as any);\n    console.log('Sign-in successful. Current auth state:', store.getState().reduxTokenAuth.currentUser);\n  } catch (error: any) {\n    console.error('Sign-in failed:', error.response?.data || error.message);\n  }\n}\n\n// Call the simulation\nif (typeof window !== 'undefined') {\n    // Only run this client-side for demonstration\n    simulateSignIn();\n}\n\n// To use generateRequireSignInWrapper, you would typically use it within a React component:\n// import { generateRequireSignInWrapper } from 'redux-token-auth';\n// const MyProtectedComponent = () => <div>Protected Content!</div>;\n// const RequireSignIn = generateRequireSignInWrapper({\n//   redirectPath: '/login', // Path to redirect if not signed in\n//   WrappedComponent: MyProtectedComponent,\n// });\n// In your router: <Route path=\"/dashboard\" component={RequireSignIn} />\n\nconsole.log('\\nQuickstart complete. Check console for output.');","lang":"typescript","description":"Demonstrates setting up the Redux store with `reduxTokenAuthReducer`, configuring `redux-token-auth` via `generateAuthActions`, dispatching initial credential verification, and simulating a user sign-in flow."},"warnings":[{"fix":"Ensure `react-router` is installed and is version 4.0.0 or greater. If not using React Router, this component cannot be utilized.","message":"The `generateRequireSignInWrapper` component (for protected routes) explicitly requires `react-router` version 4.0.0 or higher to function correctly. Using older versions or no `react-router` will lead to errors.","severity":"gotcha","affected_versions":">=0.1.0"},{"fix":"Install `redux-thunk` (`npm install redux-thunk`) and apply it to your Redux store using `createStore(rootReducer, initialState, applyMiddleware(thunk))`.","message":"The library's asynchronous actions are built upon Redux Thunk middleware. If `redux-thunk` is not integrated into your Redux store setup using `applyMiddleware`, the actions generated by `generateAuthActions` will not dispatch correctly.","severity":"gotcha","affected_versions":">=0.1.0"},{"fix":"Be aware of this limitation for React Native. For web, ensure `localStorage` is available and not blocked by browser settings or extensions.","message":"`redux-token-auth` currently supports token persistence only via `localStorage` for web applications. `AsyncStorage` for React Native environments is explicitly roadmapped but not yet implemented, meaning it's not suitable for React Native projects without custom adaptations.","severity":"gotcha","affected_versions":">=0.1.0"},{"fix":"Carefully review and provide a complete and accurate configuration object to `generateAuthActions` that matches your backend's Devise Token Auth endpoints.","message":"The `generateAuthActions` function requires a configuration object, including `apiBase`, `signInPath`, `signUpPath`, and `signOutPath`, to correctly interact with your Devise Token Auth backend. Incorrect or missing configuration will lead to failed API requests.","severity":"gotcha","affected_versions":">=0.1.0"}],"env_vars":null,"last_verified":"2026-04-22T00:00:00.000Z","next_check":"2026-07-21T00:00:00.000Z","problems":[{"fix":"Ensure `redux-thunk` is installed and passed to `applyMiddleware` when creating your Redux store, e.g., `createStore(rootReducer, applyMiddleware(thunk))`.","cause":"This error often occurs when Redux Thunk middleware is not correctly applied to the Redux store, preventing `redux-token-auth`'s asynchronous actions from being properly handled.","error":"Error: Actions may not have an undefined 'type' property. Have you misspelled a constant?"},{"fix":"Use ESM `import { reduxTokenAuthReducer } from 'redux-token-auth';` and ensure it's correctly included in `combineReducers`.","cause":"Attempting to use `require` for `reduxTokenAuthReducer` in an ESM-first environment, or incorrect destructuring of the named export.","error":"TypeError: reduxTokenAuthReducer is not a function"},{"fix":"Ensure your Redux store's initial state includes `reduxTokenAuth: { currentUser: { isLoading: false, isSignedIn: false, attributes: {} } }` or similar structure as shown in the documentation.","cause":"The initial state for the `reduxTokenAuth` reducer slice is not correctly defined in your Redux store setup.","error":"Uncaught TypeError: Cannot read properties of undefined (reading 'currentUser')"},{"fix":"Run `npm install --save redux-token-auth` or `yarn add redux-token-auth` to install the package, and double-check your import statements.","cause":"The `redux-token-auth` package has not been installed or there's a typo in the import path.","error":"Failed to compile: Can't resolve 'redux-token-auth'"}],"ecosystem":"npm"}