Installation

Install the package along with its peer dependencies.

npm install @chemmangat/msal-next @azure/msal-browser @azure/msal-react

Quick Start

1. Configure Environment

.env.local
NEXT_PUBLIC_CLIENT_ID=your-client-id
NEXT_PUBLIC_TENANT_ID=your-tenant-id

2. Wrap Your App

app/layout.tsx
import { MSALProvider } from '@chemmangat/msal-next';

export default function RootLayout({ children }) {
  return (
    <html>
      <body>
        <MSALProvider
          clientId={process.env.NEXT_PUBLIC_CLIENT_ID!}
        >
          {children}
        </MSALProvider>
      </body>
    </html>
  );
}

3. Use the Hook

app/page.tsx
'use client';

import { MicrosoftSignInButton, useMsalAuth } from '@chemmangat/msal-next';

export default function Home() {
  const { isAuthenticated, account } = useMsalAuth();

  if (!isAuthenticated) {
    return <MicrosoftSignInButton />;
  }

  return <div>Hello, {account?.name}!</div>;
}

MSALProvider

The main provider component that initializes MSAL and wraps your application.

Props

clientIdstringrequired

Azure AD Application (client) ID

tenantIdstring

Azure AD Directory (tenant) ID (optional for multi-tenant)

autoRefreshTokenbooleanNew in v4.1

Enable automatic silent token refresh

Default: false

refreshBeforeExpirynumber

Seconds before expiry to refresh token

Default: 300

useMsalAuth Hook

The main hook for authentication operations in your components.

Return Values

isAuthenticatedboolean

Whether user is authenticated

accountAccountInfo | null

Current authenticated account

loginRedirect() => Promise<void>

Login using redirect

logoutRedirect() => Promise<void>

Logout using redirect

Protected Routes (v4.0)

Protect any route with one line of code.

app/dashboard/page.tsx
export const auth = { required: true };

export default function Dashboard() {
  return <div>Protected content</div>;
}

Automatic Token Refresh (v4.1)

Prevent unexpected logouts with automatic silent token refresh.

app/layout.tsx
<MSALProvider
  clientId="..."
  autoRefreshToken={true}
  refreshBeforeExpiry={300}
>
  {children}
</MSALProvider>