next-auth-token-autologout
v1.0.6
Published
React/Next.js hook for auto logout based on JWT expiration time
Maintainers
Readme
next-auth-token-autologout
A lightweight React/Next.js hook that automatically logs out the user when their JWT token expires — based on the exp field in the token.
✨ Features
- Auto logout based on JWT expiration (
exp) - Works with React and Next.js (including NextAuth)
- Optional countdown callback (
onTick) to update the UI - Small and dependency-light
- Fully typed with TypeScript
- ✅ Zero-config JWT expiration detection
- 🔒 Auto-logout based on JWT
exptime - 🔁 Optional
onTickfor countdown behavior (e.g., show "expires in X seconds") - 🧠 Works with any auth provider (like
next-auth, Firebase, etc.)
📦 Installation
npm install next-auth-token-autologout
🧪 Example: Auto Logout in a Next.js App (Client Component)
This example uses next-auth to extract the JWT token and logs the user out automatically when it expires.
"use client";
import { TokenAutoLogout } from 'next-auth-token-autologout';
import { signOut, useSession } from 'next-auth/react';
export default function AutoLogout() {
const { data: session } = useSession();
const token = session?.apiToken ?? ''; // JWT token from your session
TokenAutoLogout({
token,
onLogout: () => {
console.log("Token expired. Logging out...");
signOut(); // Or your own logout logic
},
onTick: (msLeft) => {
console.log(`Token expires in ${Math.floor(msLeft / 1000)} seconds`);
},
tickIntervalMs: 1000, // Call onTick every second
enableLogs?: boolean; // 👈 optional, based on true n=and false check console.log for development
});
}
