Install & Compatibility
Where this runs
tested against v? · npm install
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
muslnode 18–226 runs
build_error
glibcnode 18–226 runs
build_error
Code
Verified usage
Verified import paths — ran on the pinned version, not inferred.
reduxTokenAuthReducer
✓ import { reduxTokenAuthReducer } from 'redux-token-auth';
✗ const { reduxTokenAuthReducer } = require('redux-token-auth');
This library is primarily designed for ESM consumption, shipping TypeScript types. Avoid CommonJS `require` syntax for optimal tooling.
generateAuthActions
✓ import { generateAuthActions } from 'redux-token-auth';
✗ const generateAuthActions = require('redux-token-auth').generateAuthActions;
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.
generateRequireSignInWrapper
✓ import { generateRequireSignInWrapper } from 'redux-token-auth';
✗ import generateRequireSignInWrapper from 'redux-token-auth/generateRequireSignInWrapper';
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.
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.
import { createStore, combineReducers, applyMiddleware } from 'redux';
import { thunk } from 'redux-thunk'; // Standard ESM import for redux-thunk
import { reduxTokenAuthReducer, generateAuthActions } from 'redux-token-auth';
// 1. Redux Store Setup
const rootReducer = combineReducers({
reduxTokenAuth: reduxTokenAuthReducer,
// ... potentially other reducers
});
// Define a minimal initial state structure matching redux-token-auth's expectations
const initialState = {
reduxTokenAuth: {
currentUser: {
isLoading: false,
isSignedIn: false,
attributes: {}, // Example: firstName: null
},
},
// ... any other initial state needed by other reducers
};
// Create the Redux store
// Note: In a modern React/Redux app, you'd typically use configureStore from @reduxjs/toolkit
const store = createStore(rootReducer, initialState as any, applyMiddleware(thunk));
// 2. Configure redux-token-auth and generate actions
const config = {
apiBase: 'https://api.example.com/v1', // IMPORTANT: Replace with your actual Devise Token Auth API base URL
signOutPath: '/auth/sign_out',
signInPath: '/auth/sign_in',
signUpPath: '/auth',
userAttributes: {
firstName: 'first_name',
lastName: 'last_name',
email: 'email',
},
storage: typeof window !== 'undefined' ? localStorage : null, // Use localStorage in browser, null otherwise
// You can also add authProviderPaths, etc., as needed
};
// Generate the auth actions and the verifyCredentials helper
const {
registerUser,
signInUser,
signOutUser,
verifyToken,
verifyCredentials,
} = generateAuthActions(config);
console.log('Redux Store initialized and auth actions generated.');
// 3. Dispatch verifyCredentials on application load
// This ensures the app checks for existing user tokens on startup
if (config.storage) { // Only attempt if localStorage is available (i.e., not server-side rendering)
store.dispatch(verifyCredentials() as any);
console.log('Dispatched verifyCredentials on app startup.');
}
// Example: Simulate a sign-in attempt (in a real app, this would be triggered by a user action)
async function simulateSignIn() {
console.log('\n--- Simulating User Sign-In ---');
try {
const signInPayload = { email: 'user@example.com', password: 'password123' };
// Dispatch the signInUser thunk action
// Note: Type assertion `as any` is used here for simplicity in quickstart,
// in a real app, proper ThunkAction types would be used.
await store.dispatch(signInUser(signInPayload) as any);
console.log('Sign-in successful. Current auth state:', store.getState().reduxTokenAuth.currentUser);
} catch (error: any) {
console.error('Sign-in failed:', error.response?.data || error.message);
}
}
// Call the simulation
if (typeof window !== 'undefined') {
// Only run this client-side for demonstration
simulateSignIn();
}
// To use generateRequireSignInWrapper, you would typically use it within a React component:
// import { generateRequireSignInWrapper } from 'redux-token-auth';
// const MyProtectedComponent = () => <div>Protected Content!</div>;
// const RequireSignIn = generateRequireSignInWrapper({
// redirectPath: '/login', // Path to redirect if not signed in
// WrappedComponent: MyProtectedComponent,
// });
// In your router: <Route path="/dashboard" component={RequireSignIn} />
console.log('\nQuickstart complete. Check console for output.');
Errors
Common errors & fixes
Error: Actions may not have an undefined 'type' property. Have you misspelled a constant?
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.
fixEnsure `redux-thunk` is installed and passed to `applyMiddleware` when creating your Redux store, e.g., `createStore(rootReducer, applyMiddleware(thunk))`.
TypeError: reduxTokenAuthReducer is not a function
Attempting to use `require` for `reduxTokenAuthReducer` in an ESM-first environment, or incorrect destructuring of the named export.
fixUse ESM `import { reduxTokenAuthReducer } from 'redux-token-auth';` and ensure it's correctly included in `combineReducers`. Uncaught TypeError: Cannot read properties of undefined (reading 'currentUser')
The initial state for the `reduxTokenAuth` reducer slice is not correctly defined in your Redux store setup.
fixEnsure your Redux store's initial state includes `reduxTokenAuth: { currentUser: { isLoading: false, isSignedIn: false, attributes: {} } }` or similar structure as shown in the documentation. Failed to compile: Can't resolve 'redux-token-auth'
The `redux-token-auth` package has not been installed or there's a typo in the import path.
fixRun `npm install --save redux-token-auth` or `yarn add redux-token-auth` to install the package, and double-check your import statements.
Audit
Dependencies
redux-thunkrequiredRequired for all asynchronous Redux Thunk actions (registerUser, signInUser, signOutUser, verifyToken, verifyCredentials) to function correctly.
react-routeroptionalRequired (v4.0.0+) for the `generateRequireSignInWrapper` higher-order component to provide protected routing functionality.