@kehinde-lasisi/react-native-session-timeout
v0.1.2
Published
A robust, highly customizable React Native session timeout and inactivity manager.
Maintainers
Readme
⏳ React Native Session Timeout
A robust, highly customizable React Native session timeout and inactivity manager designed to protect sensitive applications.
Built for applications that require automatic user logouts, secure inactivity tracking, background state monitoring, and interactive warning prompts.
Why Session Timeout?
Most session timeout implementations rely on basic setTimeout logic that fails when the app goes into the background or struggles to track touches globally. React Native Session Timeout goes further by:
👆 Global Interaction Tracking: Captures user touches seamlessly without interfering with underlying buttons, lists, or scroll views using PanResponder.
🌙 Background State Awareness: Intelligently monitors AppState. You can enforce stricter timeouts when the app is backgrounded or log the user out immediately.
🛡️ App Switcher Privacy Screen: Prevent sensitive data leakage (like bank balances or PHI) by rendering an opaque blur overlay over the app when it enters the background.
⏳ Time Tampering Protection: Built-in mitigations to neutralize users manually changing their device's clock to bypass timeout restrictions.
⚠️ Pre-timeout Warnings: Gracefully warn users before their session expires, allowing them to stay logged in.
⚡ Built-in UI Overlays: Optionally block the UI with customizable loading overlays while the logout process resolves.
🛡️ TypeScript Ready: First-class TypeScript support with comprehensive interfaces.
✨ Features
⏱️ Precise Inactivity Timers Configurable timeout durations that accurately track periods of inactivity across your entire application.
🎛️ Master Feature Toggle (enabled)
Seamlessly enable or disable all session timeout tracking globally (e.g. via user settings or remote feature flags) while keeping your component tree mounted.
🌙 Background & Foreground Tracking Accurately calculate how long the app was in the background. Optionally trigger immediate logouts when backgrounded.
🛡️ App Switcher Privacy Overlay Automatically obscure your app's content when users open the iOS/Android App Switcher, protecting sensitive PII and financial data.
⏳ Clock Tampering Mitigations Prevents malicious users from bypassing session limits by altering their device's system clock.
⚠️ Warning Callbacks Trigger custom alerts or modals shortly before the session expires.
🛑 Integrated Logout Loaders
Automatically render an overlay and ActivityIndicator (or a custom component) to prevent further interaction while your asynchronous logout function resolves.
📱 Platform Support
| Platform | Supported | | :---------------------------- | :-------: | | Android | ✅ | | iOS | ✅ | | React Native New Architecture | ✅ | | TypeScript | ✅ |
📦 Installation
npm install @kehinde-lasisi/react-native-session-timeout
# or
yarn add @kehinde-lasisi/react-native-session-timeoutNo native linking or pod installation required! This library relies entirely on React Native's core APIs.
🚀 Usage
Wrap your authenticated navigation or root application component with SessionTimeoutProvider.
1. Basic Inactivity Logout
Automatically log the user out after a set duration of inactivity.
import React from 'react';
import { SessionTimeoutProvider } from '@dblackdev/react-native-session-timeout';
export const App = () => {
const handleLogout = (reason: string) => {
console.log('User logged out:', reason);
// Dispatch your Redux/Context logout action here
};
return (
<SessionTimeoutProvider
isActive={true} // Only true when the user is logged in
timeoutMs={5 * 60 * 1000} // 5 minutes
onLogout={handleLogout}>
<YourAuthenticatedApp />
</SessionTimeoutProvider>
);
};2. Warning Prompts & Loaders
Warn the user before they are logged out, and display a loading spinner while the logout is processing.
import React from 'react';
import { Alert } from 'react-native';
import { SessionTimeoutProvider } from '@dblackdev/react-native-session-timeout';
export const App = () => {
const handleWarning = () => {
Alert.alert('Session Expiring', 'You will be logged out in 1 minute due to inactivity.');
};
const handleLogout = async () => {
// Simulate an API call to invalidate the token
await api.logout();
};
return (
<SessionTimeoutProvider
isActive={true}
timeoutMs={6 * 60 * 1000} // 6 minutes total
warningTimeoutMs={5 * 60 * 1000} // Warn at 5 minutes
onWarning={handleWarning}
onLogout={handleLogout}
showLoaderOnLogout={true} // Blocks UI with a spinner during `api.logout()`
loaderColor="#FF0000">
<YourAuthenticatedApp />
</SessionTimeoutProvider>
);
};3. Long-Running Tasks (Pausing & Resuming the Timer)
If a user is performing a task that should not be interrupted by session timeouts (e.g. large file upload, video processing, document scanning, or long forms), you can pause the timer. When unpaused, the timer seamlessly resumes without unfairly losing remaining session time.
Option A: Declarative via isPaused Prop
<SessionTimeoutProvider
isActive={true}
timeoutMs={5 * 60 * 1000}
isPaused={isUploadingFile} // Inactivity timer is frozen while uploading
onLogout={handleLogout}>
<YourApp />
</SessionTimeoutProvider>Option B: Programmatic via useSession() Hook
You can pause, resume, reset the timer, or read remaining time from any child component without prop-drilling:
import React from 'react';
import { View, Button, Text } from 'react-native';
import { useSession } from '@dblackdev/react-native-session-timeout';
export const UploadManagerModal = () => {
const { pause, resume, resetTimer, isPaused, getRemainingTimeMs } = useSession();
const handleStartUpload = async () => {
pause(); // Temporarily freeze timeout
try {
await uploadLargeFile();
} finally {
resume(); // Resume timer where it left off
}
};
return (
<View>
<Text>Timer Status: {isPaused ? 'Paused' : 'Active'}</Text>
<Button title="Keep Me Logged In" onPress={resetTimer} />
<Button title="Start Heavy Upload" onPress={handleStartUpload} />
</View>
);
};4. Master Feature Toggle (Enable / Disable Tracking)
Allow users or administrators to turn auto-logout functionality on or off dynamically (e.g. via app settings or remote flags) without unmounting the provider:
<SessionTimeoutProvider
enabled={userSettings.sessionTimeoutEnabled} // Set false to completely disable timers & listeners
isActive={isAuthenticated}
timeoutMs={5 * 60 * 1000}
onLogout={handleLogout}>
<YourApp />
</SessionTimeoutProvider>When enabled={false}:
- All internal timer intervals and background AppState event listeners are completely detached, eliminating native bridge overhead.
- Touch detection via
PanResponderdoes not process timer updates. useSession().isEnabledreflectsfalse.getRemainingTimeMs()safely returnsInfinity.
5. Strict Background Security & Privacy Screen
Require a shorter timeout when the app is hidden, and blur the screen in the App Switcher so the OS doesn't capture screenshots of sensitive data.
<SessionTimeoutProvider
isActive={true}
timeoutMs={10 * 60 * 1000} // 10 minutes in foreground
logoutOnBackground={false} // Don't logout *immediately* on background...
backgroundTimeoutMs={1 * 60 * 1000} // ...but logout if backgrounded for more than 1 minute
blurOnBackground={true} // Automatically covers the app with an opaque view in the App Switcher
privacyScreenStyle={{ backgroundColor: '#000000' }} // Custom black overlay
timeTamperingProtection={true} // Neutralizes system clock changes
onLogout={handleLogout}>
<YourAuthenticatedApp />
</SessionTimeoutProvider>6. Debugging & Custom Telemetry Logging
Enable console debugging or pass a custom logger to send session events directly to external monitoring tools (e.g. Sentry, Datadog, or custom logging infra):
import { SessionTimeoutProvider, SessionLogEntry } from '@dblackdev/react-native-session-timeout';
const handleSessionLog = (entry: SessionLogEntry) => {
// entry = { level: 'info' | 'warn' | 'error' | 'debug', message, timestamp, data }
if (entry.level === 'warn' || entry.level === 'error') {
Sentry.captureMessage(entry.message, { extra: entry.data });
}
};
<SessionTimeoutProvider
isActive={true}
timeoutMs={5 * 60 * 1000}
onLogout={handleLogout}
debug={__DEV__} // Pretty console output in development
logger={handleSessionLog} // Structured log telemetry callback
>
<YourApp />
</SessionTimeoutProvider>;7. Custom Messages, Z-Indexes & Colors (config)
Override default messages, overlay z-indices, and theme colors globally via the optional config prop:
<SessionTimeoutProvider
isActive={true}
timeoutMs={5 * 60 * 1000}
onLogout={handleLogout}
config={{
messages: {
timeoutMessage: 'Your session has expired due to inactivity.',
systemTamperingMessage: 'Security violation: System clock rollback detected.',
backgroundLogoutMessage: 'Session ended while app was in the background.',
},
theme: {
loaderZIndex: 10000,
privacyScreenZIndex: 100000,
privacyScreenColor: '#000000', // Full black privacy overlay
loaderOverlayColor: 'rgba(0, 0, 0, 0.8)',
loaderIndicatorColor: '#4F46E5',
},
}}>
<YourApp />
</SessionTimeoutProvider>🔒 Architecture & Security Hardening
For an in-depth breakdown of the state machine, event lifecycle, and OWASP MASVS threat model, see the Architecture Documentation.
- Cumulative Inactivity Calculation: Inactivity is strictly cumulative across foreground and background transitions. Switching or minimizing the app does not grant free session extensions.
- Error Loop Protection: If an asynchronous
onLogoutnetwork call rejects (e.g. offline token revocation failure), the provider avoids infinite retry loops and invokesonSessionTimeoutError. - PanResponder & Modal Isolation: Attaches touch listeners at the provider root. For native
<Modal>components that render in separate native window hierarchies, useuseSession()inside the modal to callresetTimer()or attach user touch handlers. - App Switcher Privacy Overlay: Obscures sensitive UI when backgrounded. Note that for strict PCI-DSS / HIPAA compliance on Android, combining this with native
FLAG_SECUREprevents OS-level screenshots and recents caching.
🚀 Common Use Cases
- 🏦 Banking and Fintech Applications: Enforcing strict regulatory timeouts.
- 🏥 Healthcare Applications (HIPAA): Securing PHI when a device is left unattended.
- 🏢 Enterprise Applications: Internal company tools requiring session management.
- 🔐 Authentication Workflows: Clearing sensitive JWTs/tokens from memory upon inactivity.
⚙️ Configuration (Props)
| Prop | Type | Default | Description |
| :------------------------ | :------------------------------------------ | :--------------------------------------- | :----------------------------------------------------------------------------- |
| enabled | boolean | true | Master toggle. When false, all timers, tracking, and listeners are disabled. |
| isActive | boolean | Required | Set to true when the user is logged in. |
| timeoutMs | number | Required | Milliseconds of inactivity before logout. |
| onLogout | (reason: string) => void \| Promise<void> | Required | Callback executed when timeout occurs. |
| timeoutMessage | string | 'Session timed out due to inactivity.' | Custom message string passed into onLogout. |
| config | SessionTimeoutConfig | undefined | Optional customization for messages, z-indexes, and colors. |
| isPaused | boolean | false | Freezes the inactivity timer during long-running tasks. |
| onSessionTimeoutError | (error: unknown) => void | undefined | Callback fired if onLogout execution rejects. |
| debug | boolean | false | Enables diagnostic console logging. |
| logger | (entry: SessionLogEntry) => void | undefined | Custom structured telemetry handler (for Sentry, Datadog). |
| warningTimeoutMs | number | undefined | Milliseconds before triggering onWarning. |
| onWarning | () => void | undefined | Executed when warningTimeoutMs is reached. |
| showLoaderOnLogout | boolean | false | Shows a UI-blocking overlay while onLogout resolves. |
| customLoader | ReactNode | undefined | Custom UI component rendered inside the logout overlay. |
| loaderColor | ColorValue | undefined | Custom color for default ActivityIndicator spinner. |
| overlayStyle | ViewStyle | undefined | Custom style for the logout loader backdrop overlay. |
| logoutOnBackground | boolean | false | If true, logs out instantly when the app is backgrounded. |
| backgroundTimeoutMs | number | timeoutMs | Stricter timeout duration (ms) for background state. |
| blurOnBackground | boolean | false | Shows a privacy overlay when the app is inactive/backgrounded. |
| privacyScreenStyle | ViewStyle | undefined | Custom styles (e.g. background color) for the privacy screen. |
| privacyScreenComponent | ReactNode | undefined | Custom component to render inside the privacy screen. |
| timeTamperingProtection | boolean | false | Enforces logouts on negative clock jumps and mitigates clock tampering. |
| disableTimer | boolean | false | (Deprecated) Use isPaused instead. |
🪝 useSession() Hook API
The useSession() hook can be called from any child component rendered within <SessionTimeoutProvider>:
| Property | Type | Description |
| :------------------- | :------------- | :------------------------------------------------------------------------------------------------- |
| resetTimer | () => void | Resets the inactivity timer to 0 elapsed time. Useful in modals or custom touchable surfaces. |
| pause | () => void | Freezes the inactivity timer during long-running tasks (e.g. file uploads). |
| resume | () => void | Resumes a previously paused timer right where it left off. |
| isEnabled | boolean | Indicates whether session timeout management is globally enabled via the enabled prop. |
| isPaused | boolean | Indicates whether the session timer is currently paused. |
| getRemainingTimeMs | () => number | Returns the remaining time in ms before session timeout (returns Infinity if enabled={false}). |
👤 Author
Developed and maintained by dblackdev ([email protected]).
📄 License
MIT
Keywords
react-native session timeout inactivity security authentication auto-logout app-state background-timer pan-responder auth fintech enterprise
