react-ad-auth
v1.0.1
Published
Simplified Azure AD authentication for React and Next.js
Maintainers
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 | nulluseAccessToken()
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:3000Azure AD Setup
- Go to Azure Portal
- Navigate to Azure Active Directory > App registrations
- Click "New registration"
- Configure:
- Name: Your app name
- Supported account types: Choose based on your needs
- Redirect URI:
http://localhost:3000(for development)
- Copy the Application (client) ID and Directory (tenant) ID
- Under "Authentication":
- Enable "ID tokens"
- Add redirect URIs for production
- 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
