DEV Community

Hari Manoj
Hari Manoj

Posted on

I added Microsoft Auth to my Next.js app in 5 minutes. Here's how.

No, seriously. One command.

npx @chemmangat/msal-next-cli init
Enter fullscreen mode Exit fullscreen mode

That's it. It asks you three questions, writes your .env.local, wires up layout.tsx, and creates a starter auth page. You didn't misread that.


The problem with MSAL in Next.js

If you've tried it before, you know. The official docs are verbose. Middleware breaks on the edge runtime. Token expiry is hardcoded. Cookie sync is manual. And MSAL v5 just dropped with enough breaking changes to ruin your afternoon.

@chemmangat/msal-next fixes all of that.


What v5.3.0 ships

  • Auto cookie syncMsalAuthProvider now writes and clears msal.account on every login/logout automatically. Middleware works with zero manual setup.
  • Edge runtime fixedcreateAuthMiddleware now lives in its own import path, no more Next.js edge crashes.
  • Real token expiry — reads actual expiresOn from the token. No more hardcoded 3600 seconds sneaking up on you in prod.
  • MSAL v3, v4, v5 all supported — runtime version detection. You update MSAL, nothing breaks.

The whole auth setup, start to finish

npm install @chemmangat/msal-next @azure/msal-browser @azure/msal-react
Enter fullscreen mode Exit fullscreen mode
// 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>
  );
}
Enter fullscreen mode Exit fullscreen mode
// 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>;
}
Enter fullscreen mode Exit fullscreen mode

That's the full implementation. Sign in with Microsoft, working.


Already using it? Upgrading to MSAL v5?

npm install @azure/msal-browser@latest @azure/msal-react@latest
Enter fullscreen mode Exit fullscreen mode

Done. Every v5 breaking change is handled internally — event payload types, removed config options, redirect promise signature. You change nothing in your app code.


It also does...

  • Multi-account support (switch between 5 Microsoft accounts)
  • Multi-tenant control — allow/block by domain or tenant ID
  • Protected routes in one line
  • Auto token refresh — no more surprise logouts
  • 100% TypeScript, 2.9k+ weekly downloads

Sounds too good to be true? Try it.

📦 npmjs.com/package/@chemmangat/msal-next
🌐 msal.chemmangathari.in

Top comments (0)