{"id":27983,"library":"next-jwt-auth","title":"Next JWT Auth","description":"Next JWT Auth is a lightweight React/Next.js library for integrating custom JWT authentication services hosted separately from your Next.js app. Version 1.5.0 provides a simple provider-based pattern to manage JWT access and refresh tokens, using browser cookies for storage and automatically refreshing tokens when they expire. Unlike NextAuth.js, it does not create API routes inside your Next.js app, avoiding an extra hop between frontend and auth service, and focuses solely on JWT auth without support for social login or database adapters. The library requires Next.js ^16.2.4, React >=18, and Axios ^1.6.8 as peer dependencies. It ships with TypeScript types and is actively maintained, with frequent releases (latest v1.5.0 as of April 2025). Key differentiators: direct frontend-to-auth-service calls, automatic token refresh and logout, and minimal boilerplate.","status":"active","version":"1.5.0","language":"javascript","source_language":"en","source_url":"https://github.com/palatok/next-jwt-auth","tags":["javascript","react","nextjs","jwt","auth","typescript"],"install":[{"cmd":"npm install next-jwt-auth","lang":"bash","label":"npm"},{"cmd":"yarn add next-jwt-auth","lang":"bash","label":"yarn"},{"cmd":"pnpm add next-jwt-auth","lang":"bash","label":"pnpm"}],"dependencies":[{"reason":"Peer dependency used for HTTP requests to the external auth service","package":"axios","optional":true},{"reason":"Peer dependency required for Next.js framework features (pages router, server components)","package":"next","optional":true},{"reason":"Peer dependency needed for React components and hooks","package":"react","optional":true}],"imports":[{"note":"TypeScript type import; ESM only. CommonJS not supported.","wrong":"const { JWTAuthConfig } = require('next-jwt-auth')","symbol":"JWTAuthConfig","correct":"import { JWTAuthConfig } from 'next-jwt-auth'"},{"note":"Named export, not default. Used as base type for user interface.","wrong":"import AuthUser from 'next-jwt-auth'","symbol":"AuthUser","correct":"import { AuthUser } from 'next-jwt-auth'"},{"note":"Factory function to create a custom provider component. Must use named import.","symbol":"createJWTAuthProvider","correct":"import { createJWTAuthProvider } from 'next-jwt-auth'"},{"note":"The hook is named useJWTAuth, not useAuth. It returns user, login, logout, isAuthenticated.","wrong":"import { useAuth } from 'next-jwt-auth'","symbol":"useJWTAuth","correct":"import { useJWTAuth } from 'next-jwt-auth'"}],"quickstart":{"code":"// src/types/Auth.ts\nimport { AuthUser } from 'next-jwt-auth'\n\nexport interface LoggedInUser extends AuthUser {\n  email: string\n  firstName: string\n  lastName: string\n  phone: string\n}\n\n// src/config/Auth.ts\nimport { JWTAuthConfig, createJWTAuthProvider, useJWTAuth } from 'next-jwt-auth'\n\nconst authConfig: JWTAuthConfig = {\n  apiBaseUrl: process.env.NEXT_PUBLIC_API_BASE_URL ?? 'http://localhost:4000',\n  user: { property: 'user' },\n  accessToken: { property: 'access.token' },\n  refreshToken: { property: 'refresh.token' },\n  login: {\n    url: '/auth/signin',\n    method: 'POST',\n    body: { email: '', password: '' }\n  },\n  refresh: { url: '/auth/refresh', method: 'POST' },\n  logout: { url: '/auth/logout', method: 'POST' },\n  cookieOptions: { httpOnly: false, secure: true, sameSite: 'strict' }\n}\n\nexport const { AuthProvider, useAuth } = createJWTAuthProvider<LoggedInUser>(authConfig)\n\n// pages/_app.tsx\nimport { AuthProvider } from '../config/Auth'\n\nfunction MyApp({ Component, pageProps }) {\n  return (\n    <AuthProvider>\n      <Component {...pageProps} />\n    </AuthProvider>\n  )\n}\n\nexport default MyApp\n\n// pages/profile.tsx\nimport { useAuth } from '../config/Auth'\n\nexport default function Profile() {\n  const { user, login, logout, isAuthenticated } = useAuth()\n\n  const handleLogin = async () => {\n    await login({ email: 'user@example.com', password: 'pass123' })\n  }\n\n  return (\n    <div>\n      {isAuthenticated ? (\n        <>\n          <p>Welcome, {user?.firstName}</p>\n          <button onClick={logout}>Logout</button>\n        </>\n      ) : (\n        <button onClick={handleLogin}>Login</button>\n      )}\n    </div>\n  )\n}","lang":"typescript","description":"Demonstrates setup with custom user type, config, provider wrapper, and login/logout using the useAuth hook."},"warnings":[{"fix":"Upgrade Next.js to >=16.2.4 or use next-jwt-auth@1.3.0 for Next.js 14 support.","message":"Requires Next.js ^16.2.4 (previously supported ^14.1.4). Update Next.js or pin to older version.","severity":"breaking","affected_versions":">=1.4.0"},{"fix":"Set 'redirect.afterLogin' in authConfig instead of passing a second argument to login().","message":"The 'login' method no longer accepts a callback URL; use the 'redirect' config option instead.","severity":"deprecated","affected_versions":">=1.5.0"},{"fix":"Use the 'onTokenExpired' callback in authConfig to trigger logout.","message":"The 'logout' method no longer logs out automatically on refresh token expiry; you must manually check 'isTokenExpired'.","severity":"deprecated","affected_versions":">=1.5.0"},{"fix":"Install axios@1.6.8: npm install axios@1.6.8","message":"Axios peer dependency must be exactly ^1.6.8. Using a different version may cause import errors.","severity":"gotcha","affected_versions":">=1.0.0"},{"fix":"Set 'cookieOptions.httpOnly: true' if your auth service sets cookies server-side, or use a backend proxy for sensitive tokens.","message":"Cookies are set with httpOnly: false by default, making them accessible to JavaScript (XSS risk).","severity":"gotcha","affected_versions":">=1.0.0"}],"env_vars":null,"last_verified":"2026-05-09T00:00:00.000Z","next_check":"2026-08-07T00:00:00.000Z","problems":[{"fix":"Verify that authConfig.accessToken.property matches the exact nested path in your API response (e.g., 'access.token' for { access: { token: '...' } }).","cause":"The access token property path in response does not match 'accessToken.property' config.","error":"Uncaught TypeError: Cannot read properties of undefined (reading 'token')"},{"fix":"Ensure your auth service returns 'expiresAt' as an ISO 8601 string (e.g., '2025-12-31T23:59:59Z') or a Unix timestamp (number).","cause":"The 'expiresAt' field in the API response is missing or not a valid date format.","error":"next-jwt-auth: Failed to parse token expiry. Please provide a valid date string or timestamp."},{"fix":"Run npm install next-jwt-auth from the project root. Ensure your build tool resolves node_modules correctly.","cause":"Library not installed, or installed in wrong directory (e.g., not in same package.json as the importing code).","error":"Module not found: Can't resolve 'next-jwt-auth' in '/path/to/project'"},{"fix":"Wrap your app with <AuthProvider> at the top level (e.g., in _app.tsx) and only call useAuth() inside children of the provider.","cause":"useJWTAuth or useAuth called outside of a React component or before the AuthProvider is mounted.","error":"Error: Invalid hook call. Hooks can only be called inside of the body of a function component."},{"fix":"Change to 'import type { AuthUser } from 'next-jwt-auth'' or use 'import { type AuthUser } from 'next-jwt-auth''.","cause":"Importing AuthUser as a value instead of a type (type-only import needed).","error":"TypeScript error: 'AuthUser' is declared but its value is never read."}],"ecosystem":"npm","meta_description":null,"install_score":null,"install_tag":null,"quickstart_score":null,"quickstart_tag":null}