react-redux-django-auth
v1.9.9
Published
A React Redux Authentication system for django app built with TypeScript.
Maintainers
Readme
React-Redux Django Authentication Hooks
This package provides a suite of custom React and React Native hooks, alongside a Redux Provider, to streamline authentication with a Django backend. By integrating directly with Redux, it offers a predictable state management solution for handling user authentication status, data, and errors across both Web and Mobile platforms.
Features
Installation
Install the package and its peer dependencies via npm or yarn:
npm install react-redux-django-auth react-redux redux axiosor using yarn:
yarn add react-redux-django-auth react-redux redux axiosReact Native Peer Dependencies
If you are using React Native, you will also need to install specific peer dependencies for secure storage and biometrics:
# Using Expo:
npx expo install expo-secure-store expo-local-authentication
# Or equivalent bare React Native packages depending on your setup.1. Setup Auth Provider
The first step to activating the ecosystem is to wrap your application root with the appropriate platform-specific AuthProvider. The package manages internal authentication state and storage abstractions contextually based on the wrapper you choose (localStorage handles the state contract for Web, while SecureStore locks down tokens on Mobile).
Provider Props Configuration API
The provider layer accepts the following property options to customize your authentication workspace instance on startup:
apiUrl[string](Required): The base URL gateway pointing directly to your backend service.authTokenType['JWT' | 'Bearer'](Optional): The token string prefix appended automatically to outgoing secure authorization headers. Defaults to'JWT'.authEndpoints[AuthEndpoints](Optional): An object mapping matching your custom Django routing setup to override the core fallback paths. Defaults to:
const defaultEndpoints: Required<AuthEndpoints> = {
login: 'auth/jwt/create/',
refresh: 'auth/jwt/refresh/',
loadUser: 'auth/users/me/',
verify: 'auth/jwt/verify/',
signup: 'auth/users/',
activation: 'auth/users/activation/',
resetPassword: 'auth/users/reset_password/',
resetPasswordConfirm: 'auth/users/reset_password_confirm/',
facebook: 'auth/o/facebook/',
google: 'auth/o/google-oauth2/',
setPassword: 'auth/users/set_password/',
resendEmailActivation: 'auth/users/resend_activation/',
deleteUser: 'auth/users/me/',
mobileGoogle: 'auth/google-oauth2-mobile/',
logout: 'auth/jwt/blacklist/',
webGoogle: 'auth/o/google-oauth2/',
webFacebook: 'auth/o/facebook/',
};extraHeaders[Record<string, string>](Optional): A dynamic key-value lookup object used to pass specialized network settings (such as local proxy settings or version variables) straight to the internal connection instances.
Implementation for Web Projects (React / Next.js)
Import AuthProvider from the web submodule package path and mount it around your main router tree inside your application entry file (e.g., index.tsx or main.js):
import React from 'react';
import ReactDOM from 'react-dom/client';
import { BrowserRouter } from 'react-router-dom';
import App from './App';
import { AuthProviderWeb } from 'react-redux-django-auth/web';
const root = ReactDOM.createRoot(document.getElementById('root') as HTMLElement);
const BASE_URL = process.env.REACT_APP_API_URL || "https://api.yourdomain.com/v1";
root.render(
<React.StrictMode>
<BrowserRouter>
<AuthProviderWeb
apiUrl={BASE_URL}
authTokenType="Bearer"
authEndpoints={{
login: 'auth/email/login/',
loadUser: 'auth/user/details/',
signup: 'auth/user/register/',
}}
extraHeaders={{
'X-Client-Platform': 'Web-Browser'
}}
>
<App />
</AuthProviderWeb>
</BrowserRouter>
</React.StrictMode>
);
Implementation for Mobile Projects (React Native / Expo)
Import AuthProviderNative from the native submodule package path and encapsulate your root navigation slot layout component (e.g., in Expo Router's _layout.tsx or bare-metal App.tsx entry points):
import React from "react";
import { Slot } from "expo-router";
import { AuthProviderNative } from "react-redux-django-auth/native";
export default function RootLayout() {
const BASE_URL = process.env.EXPO_PUBLIC_API_URL || "https://api.yourdomain.com/v1";
return (
<AuthProviderNative
apiUrl={BASE_URL}
authTokenType="Bearer"
authEndpoints={{
login: 'auth/email/login/',
refresh: 'auth/token/refresh/',
loadUser: 'auth/user/details/',
signup: 'auth/user/register/',
}}
extraHeaders={{
// 🟢 Bypasses local development ngrok warning screens seamlessly!
'ngrok-skip-browser-warning': 'true'
}}
>
<Slot />
</AuthProviderNative>
);
}
By completing this step, the global store provider automatically coordinates all platform storage handshake mechanisms. Any descendant component or screen layout within your tree hierarchy can now consume authentication state, handle form validation loops, and run state methods cleanly through the package hooks.
2. Core Authentication Hooks
All core hooks are platform-agnostic and can be imported directly from the main package (react-redux-django-auth). These hooks manage form data, loading states, Redux dispatching, and error handling out-of-the-box.
useLogin
Manages the state and logic for a login form.
import { useLogin } from "react-redux-django-auth";
const LogIn = () => {
const initialFormData = { email: "", password: "" };
const { error, formData, isStatus200, loading, onChange, onSubmit } =
useLogin(initialFormData);
return (
<form onSubmit={onSubmit}>
<input type="email" name="email" value={formData.email} onChange={onChange} required />
<input type="password" name="password" value={formData.password} onChange={onChange} required />
<button type="submit" disabled={loading}>
{loading ? "Logging In..." : "Log In"}
</button>
{error && <div className="error">{error}</div>}
</form>
);
};useSignup
Manages the state and logic for a user registration form.
import { useSignup } from "react-redux-django-auth";
const Signup = () => {
const initialFormData = { email: "", password: "", re_password: "" };
const { error, formData, isStatus201, loading, onChange, onSubmit } =
useSignup(initialFormData);
return (
<form onSubmit={onSubmit}>
<input type="email" name="email" value={formData.email} onChange={onChange} required />
<input type="password" name="password" value={formData.password} onChange={onChange} required />
<input type="password" name="re_password" value={formData.re_password} onChange={onChange} required />
<button type="submit" disabled={loading}>
{loading ? "Signing Up..." : "Sign Up"}
</button>
{error && <div className="error">{error}</div>}
</form>
);
};useAuthicatedUser
Manages the user's authentication status and profile data. Use this hook to protect routes and conditionally render content.
import { useAuthicatedUser } from "react-redux-django-auth";
const Dashboard = () => {
// Use the hook to fetch the authenticated user data automatically
const { isAuthenticated, currentUser, error, refreshUser, isLoading } =
useAuthicatedUser();
if (isLoading) return <div>Loading Profile...</div>;
if (!isAuthenticated) return <div>Please Log In.</div>;
return (
<div>
<h1>Welcome, {currentUser?.name}!</h1>
<button onClick={refreshUser}>Refresh Profile Data</button>
{error && <div className="error">{error}</div>}
</div>
);
};useLogout
A straightforward hook designed to handle user logout by clearing the Redux authentication state.
import { useLogout } from "react-redux-django-auth";
const UserProfile = () => {
const logout = useLogout();
return (
<div>
<button onClick={logout}>Log Out</button>
</div>
);
};useActivate
Handles the user account activation process (e.g., from an email link). Extract uid and token from the URL parameters to pass them in.
import { useActivate } from "react-redux-django-auth";
import { useParams } from "react-router-dom";
const ActivateAccount = () => {
const { uid, token } = useParams();
const { error, loading, onSubmit, isStatus204 } = useActivate(uid, token);
return (
<button onClick={onSubmit} disabled={loading}>
{loading ? "Verifying..." : "Verify Account"}
</button>
);
};Password Management Hooks
useResetPassword: Manages the request for a password reset email.usePasswordConfirm: Confirms a new password using theuidandtokenafter a reset.useChangeAuthenticatedUserPassword: Changes the password for a user who is currently logged in.
3. React Native Specific Features
useBiometricAuth
React Native supports biometric authentication (FaceID/TouchID/Fingerprint) out of the box. This hook securely stores credentials and uses biometrics to automatically log users in. Import it specifically from /native.
import React, { useEffect } from "react";
import { View, ActivityIndicator, Text } from "react-native";
import { useAuthicatedUser } from "react-redux-django-auth";
import { useBiometricAuth } from "react-redux-django-auth/native"; // Native-specific import
import { useNavigation } from "@react-navigation/native";
const SplashScreen = () => {
const navigation = useNavigation();
const API_URL = "https://api.yourdomain.com/v1";
const { isAuthenticated, currentUser, isLoading, refreshAuth } =
useAuthicatedUser(API_URL);
const { authenticate, loading: bioLoading } = useBiometricAuth({
apiUrl: API_URL,
});
useEffect(() => {
const initAuth = async () => {
try {
// Attempt biometric login if not already authenticated
if (!isAuthenticated) {
await authenticate(); // Handles local auth logic internally
await refreshAuth(); // Re-check auth and load user into redux
}
// Navigate based on auth status
if (currentUser) {
navigation.reset({ index: 0, routes: [{ name: "Home" }] });
} else {
navigation.reset({ index: 0, routes: [{ name: "Login" }] });
}
} catch (err) {
console.log("Biometric/Auth failed:", err);
navigation.reset({ index: 0, routes: [{ name: "Login" }] });
}
};
initAuth();
}, [isAuthenticated, currentUser]);
if (isLoading || bioLoading) {
return (
<View style={{ flex: 1, justifyContent: "center", alignItems: "center" }}>
<ActivityIndicator size="large" />
<Text>Loading...</Text>
</View>
);
}
return null;
};4. OAuth Setup
The package also exposes hooks for handling OAuth with Google and Facebook:
useGoogleAuth / useFacebookAuth
These hooks provide a streamlined way to authenticate using social platforms. Web-specific OAuth logic is exported from /web while Native logic may be adapted specifically via /native.
import { useGoogleAuth } from "react-redux-django-auth/web";
import { useFacebookAuth } from "react-redux-django-auth";
import { useGoogleAuthNative } from "react-redux-django-auth/native";