npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

react-ad-auth

v1.0.1

Published

Simplified Azure AD authentication for React and Next.js

Readme

react-ad-auth

A simplified authentication library for integrating Azure AD (Microsoft Entra ID) into React and Next.js applications. Built to streamline the authentication experience and reduce boilerplate code.

Author: Nneka Ezema

Features

  • Zero Config Complexity - Set up authentication in minutes, not hours
  • TypeScript First - Full type safety and IntelliSense support out of the box
  • Next.js Optimized - Works seamlessly with App Router, Pages Router, and API routes
  • Protected Routes - Easy route protection with components or middleware
  • Role-Based Access Control - Built-in RBAC support for managing user permissions
  • Token Management - Automatic token refresh and secure caching
  • SSR Compatible - Full server-side authentication support
  • Production Ready - Built on top of Microsoft's official MSAL library

Installation

react-ad-auth

or

yarn add react-ad-auth

or

pnpm add react-ad-auth


##

##  Quick Start

### 1. Wrap Your App with AuthProvider

**Next.js App Router (app/layo*
```tsx
import { AuthProvider } from '@switch/react-ad-auth';

export default function RootLayout({ children }) {
  return (
    <html lang="en">
      <body>
        <AuthProvider
          tenantId={process.env.NEXT_PUBLIC_AZURE_AD_TENANT_ID!}
          clientId={process.env.NEXT_PUBLIC_AZURE_AD_CLIENT_ID!}
          redirectUri={process.env.NEXT_PUBLIC_REDIRECT_URI}
        >
          {children}
        </AuthProvider>
      </body>
    </html>
  );
}

Next.js Pages Router (_app.tsx)

import { AuthProvider } from 'react-ad-auth';
import type { AppProps } from 'next/app';

export default function App({ Component, pageProps }: AppProps) {
  return (
    <AuthProvider
      tenantId={process.env.NEXT_PUBLIC_AZURE_AD_TENANT_ID!}
      clientId={process.env.NEXT_PUBLIC_AZURE_AD_CLIENT_ID!}
    >
      <Component {...pageProps} />
    </AuthProvider>
  );
}

2. Use Authentication in Components

import { useAuth } from 'react-ad-auth';

export default function Dashboard() {
  const { user, isAuthenticated, login, logout, isLoading } = useAuth();

  if (isLoading) return <div>Loading...</div>;

  if (!isAuthenticated) {
    return (
      <button onClick={login}>
        Sign In with Microsoft
      </button>
    );
  }

  return (
    <div>
      <h1>Welcome, {user?.name}!</h1>
      <p>Email: {user?.email}</p>
      <button onClick={logout}>Sign Out</button>
    </div>
  );
}

Protected Routes

Component-based Protection

import { ProtectedRoute } from 'react-ad-auth';

export default function DashboardPage() {
  return (
    <ProtectedRoute>
      <DashboardContent />
    </ProtectedRoute>
  );
}

Role-based Protection

import { RequireRole } from 'react-ad-auth';

export default function AdminPage() {
  return (
    <RequireRole roles={['Admin', 'SuperUser']}>
      <AdminPanel />
    </RequireRole>
  );
}

// Require ALL roles
export default function SecurePage() {
  return (
    <RequireRole roles={['Admin', 'Auditor']} requireAll>
      <SecureContent />
    </RequireRole>
  );
}

Next.js Middleware

middleware.ts

import { authMiddleware } from 'react-ad-auth/nextjs';

export default authMiddleware({
  protectedRoutes: ['/dashboard', '/profile', '/admin'],
  publicRoutes: ['/', '/about', '/contact'],
  roleBasedRoutes: {
    '/admin': ['Admin'],
    '/reports': ['Admin', 'Manager']
  },
  loginUrl: '/login'
});

export const config = {
  matcher: ['/((?!api|_next/static|_next/image|favicon.ico).*)']
};

API Route Protection

app/api/data/route.ts

import { getServerAuth } from 'react-ad-auth/server';
import { NextRequest } from 'next/server';

export async function GET(request: NextRequest) {
  const auth = await getServerAuth();
  
  if (!auth.isAuthenticated) {
    return Response.json({ error: 'Unauthorized' }, { status: 401 });
  }

  const { user, accessToken } = auth;
  
  return Response.json({ 
    message: 'Protected data',
    user: user?.name 
  });
}

Access Token Usage

import { useAccessToken } from 'react-ad-auth';

export function DataFetcher() {
  const { getAccessToken } = useAccessToken();

  const fetchData = async () => {
    const token = await getAccessToken(['https://graph.microsoft.com/.default']);
    
    const response = await fetch('https://graph.microsoft.com/v1.0/me', {
      headers: {
        'Authorization': `Bearer ${token}`
      }
    });
    
    return response.json();
  };

  return <button onClick={fetchData}>Fetch User Data</button>;
}

Configuration Options

<AuthProvider
  tenantId="your-tenant-id"              // Required
  clientId="your-client-id"              // Required
  redirectUri="http://localhost:3000"    // Optional
  scopes={['User.Read', 'Mail.Read']}   // Optional
  cacheLocation="sessionStorage"         // Optional: 'localStorage' | 'sessionStorage'
  loginMode="popup"                      // Optional: 'popup' | 'redirect'
  onLoginSuccess={(user) => {}}          // Optional
  onLoginError={(error) => {}}           // Optional
  onLogout={() => {}}                    // Optional
>
  {children}
</AuthProvider>

Hooks API

useAuth()

const {
  user,              // User object or null
  isAuthenticated,   // Boolean
  isLoading,         // Boolean
  login,             // () => Promise<void>
  logout,            // () => Promise<void>
  getAccessToken,    // (scopes?) => Promise<string>
  hasRole,           // (role: string | string[]) => boolean
  hasAllRoles,       // (roles: string[]) => boolean
  hasAnyRole,        // (roles: string[]) => boolean
} = useAuth();

useUser()

const user = useUser(); // User | null

useAccessToken()

const { getAccessToken } = useAccessToken();
const token = await getAccessToken(['scope1', 'scope2']);

Environment Variables

Create a .env.local file:

NEXT_PUBLIC_AZURE_AD_TENANT_ID=your-tenant-id
NEXT_PUBLIC_AZURE_AD_CLIENT_ID=your-client-id
NEXT_PUBLIC_REDIRECT_URI=http://localhost:3000

Azure AD Setup

  1. Go to Azure Portal
  2. Navigate to Azure Active Directory > App registrations
  3. Click "New registration"
  4. Configure:
    • Name: Your app name
    • Supported account types: Choose based on your needs
    • Redirect URI: http://localhost:3000 (for development)
  5. Copy the Application (client) ID and Directory (tenant) ID
  6. Under "Authentication":
    • Enable "ID tokens"
    • Add redirect URIs for production
  7. Under "API permissions":
    • Add required Microsoft Graph permissions
    • Grant admin consent if needed

Examples

Check out the /examples folder for complete working examples:

  • Basic React app
  • Next.js App Router
  • Next.js Pages Router
  • Role-based access control
  • Server-side rendering

Contributing

Contributions are welcome! Feel free to open issues or submit pull requests.

License

MIT

Support

  • Issues: I'll provide later
  • NPM: https://www.npmjs.com/package/react-ad-auth

Built by Nneka Ezema for better developer experience