Next Protected Auth

2.0.450 · active · verified Wed Apr 22

Next Protected Auth is a JavaScript/TypeScript library designed to simplify the implementation of protected routes and authentication flows within Next.js applications. It provides a set of React components and hooks that abstract common authentication logic for login, logout, and auth callbacks, aiming to reduce boilerplate in Next.js projects. The current stable version is 2.0.450, indicating active maintenance with frequent patch releases, aligning with updates in the Next.js ecosystem. While not a full-fledged authentication provider like Auth.js (formerly NextAuth.js), it focuses specifically on the client-side integration of existing authentication systems with Next.js's routing and middleware for securing routes and managing user sessions. It differentiates itself by providing granular, component-based control over authentication UI and logic hooks.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to integrate `next-protected-auth` into a Next.js Pages Router application (`_app.tsx`), using the `useNextAuthProtectedHandler` hook to manage global route protection, public URLs, and token validation logic. It also shows basic usage of the `NextAuthProtectedLogin` component for initiating an authentication flow.

import { useNextAuthProtectedHandler, NextAuthProtectedLogin } from 'next-protected-auth';
import { useRouter } from 'next/router';
import type { AppProps } from 'next/app';
import { useEffect } from 'react';

// This setup is typically for Next.js Pages Router in pages/_app.tsx
// For App Router, you'd integrate the handler within middleware or a root layout.
export default function MyApp({ Component, pageProps }: AppProps) {
  const router = useRouter();

  // Configure the authentication handler for route protection
  const { isConnected, setIsConnected } = useNextAuthProtectedHandler({
    publicURLs: ['/', '/about', '/auth/login', '/auth/callback'],
    loginURL: '/auth/login',
    authCallbackURL: '/auth/callback',
    renewTokenFct: (oldAccessToken?: string) => {
      // Implement your token renewal logic here, e.g., an API call to refresh tokens
      console.log('Attempting to renew token:', oldAccessToken);
      // In a real app, this would be an async operation returning a new token or throwing an error.
      return 'new-mock-access-token'; // Return the new access token
    },
    verifyTokenFct: (accessToken?: string) => {
      // Implement your token verification logic here, e.g., check JWT expiration locally or via an API
      console.log('Verifying token:', accessToken);
      // Return a string indicating validity ('valid', 'expired', etc.) or empty if invalid
      return accessToken && accessToken !== 'expired-token' ? 'valid' : '';
    },
    allowNotFound: true, // Allows unauthenticated users to see 404 pages
  });

  useEffect(() => {
    // Example: React to connection status for UI updates or additional redirects
    if (isConnected) {
      console.log('User is authenticated!');
    } else {
      console.log('User is not authenticated.');
    }
  }, [isConnected]);

  // Render specific authentication components based on the current path
  if (router.pathname === '/auth/login') {
    return (
      <NextAuthProtectedLogin
        callback={() => {
          console.log('Login initiated. Redirecting user to OAuth provider...');
          // Example: window.location.href = process.env.NEXT_PUBLIC_OAUTH_LOGIN_URL ?? '';
        }}
        authCallbackURL="/auth/callback"
      />
    );
  }

  // Render the main application component
  return <Component {...pageProps} />;
}

view raw JSON →