{"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.","language":"javascript","status":"active","last_verified":"Wed Apr 22","install":{"commands":["npm install redux-token-auth"],"cli":null},"imports":["import { reduxTokenAuthReducer } from 'redux-token-auth';","import { generateAuthActions } from 'redux-token-auth';","import { generateRequireSignInWrapper } from 'redux-token-auth';"],"auth":{"required":false,"env_vars":[]},"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.","tag":null,"tag_description":null,"last_tested":null,"results":[]},"compatibility":null}