I originally published this repository as MsalWithNextJs14 to demonstrate Microsoft authentication in the Next.js App Router. My main application kept moving forward, but I did not have enough time to bring those changes back into the public sample.
Eventually, the repository needed more than a dependency update. I wanted to bring back the reusable authentication improvements, remove application-specific assumptions, and make the sample useful with a newer version of Next.js.
With more than 60 stars on the original repository, I also wanted to preserve its history and the links people already had. I renamed the existing repository to nextjs-msal-app-router, keeping its stars, forks, and commit history. The name now describes the integration without tying it to one framework release.
This article walks through the updated implementation: where MSAL belongs in the App Router, how I coordinate startup and redirects, how token requests behave under concurrency, and what the role checks actually protect.
The examples refer to this revision of the repository, so the explanations remain traceable as the project changes.
The versions and scope of this update
This revision uses the following package versions:
| Package | Version |
|---|---|
| Next.js | 16.5.0 |
| React and React DOM | 19.3.1 |
| MSAL Browser | 4.30.0 |
| MSAL React | 3.0.29 |
| TypeScript | 5.9.3 |
The MSAL packages are declared with compatible version ranges, and the lockfile records the versions above. I kept the MSAL Browser 4 and MSAL React 3 integration used by this implementation. The framework upgrade should not be read as a migration to every library's newest major version.
The sample has three routes:
| Route | Purpose |
|---|---|
/ | Show the signed-in experience and role summary |
/adminonlypage | Demonstrate conditional rendering based on app roles |
/gettokentest | Request an API access token through an explicit user action |
I kept the scope focused on browser authentication with Microsoft Entra ID. There is no backend session implementation or protected business API in this repository. That boundary matters throughout the design.
Where MSAL belongs in the App Router
Next.js layouts and pages are Server Components by default. Interactive components use client boundaries for hooks, events, and browser APIs. That makes the placement of the authentication provider an architectural decision. Next.js explains these boundaries in its Server and Client Components guide.
My root layout stays a Server Component. It renders the public page structure and places the authentication wrapper around the session controls and page content:
The browser owns the MSAL client, its account cache, and its interaction state. The server does not receive a trusted application session just because this provider exists.
This has a consequence that is easy to miss: wrapping a Server Component in a client-side authentication boundary does not make the Server Component's output private. Server work can already have happened, and data can be included in the response sent to the browser. The sample therefore keeps that content public and demonstrative.
If I were serving private data from a Server Component, Route Handler, or Server Action, I would authorize that request on the server before reading or returning the data. A browser role wrapper cannot do that work.
Public configuration without private application values
The repository includes an empty .env.example:
The client ID and tenant ID are required. The API scope is optional until the token demo is used. The role setting is optional and defaults to the sample role value Sample.Admin.
These are public browser settings. Next.js substitutes NEXT_PUBLIC_ values into the client bundle at build time. Keeping the local environment file out of Git avoids accidentally committing deployment configuration, but it does not make those browser values secret. Changing them for a production deployment requires rebuilding the bundle. Next.js documents this build-time behavior.
There is no client secret in this integration. The browser uses the authorization code flow with PKCE through MSAL. A browser application cannot keep a confidential client credential, and Microsoft documents the SPA redirect configuration required for this flow. See the Microsoft identity platform authorization code flow guide.
Before constructing the client, I validate that the client and tenant IDs have GUID syntax. Missing or malformed values produce a setup screen. That makes a fresh checkout usable without immediately sending someone into a failed sign-in redirect. This is format validation; it cannot confirm that an app registration exists or that its permissions are correct.
The configuration uses a tenant-specific authority and builds both redirect URLs from the current browser origin, with / as the callback path. For local development, the registered SPA redirect URI is http://localhost:3000/. Each deployed origin needs its corresponding root callback registered as well.
This is deliberately a tenant-specific, origin-root sample. A deployment under a Next.js basePath, an account model spanning multiple tenants, or a different Microsoft cloud needs corresponding configuration changes.
I also use session storage for the MSAL cache and disable SDK logging in the sample. Neither choice removes the need to prevent cross-site scripting. The browser still handles authentication material.
Creating the client only when the browser is ready
Adding "use client" does not mean I can safely construct a browser-dependent SDK at module import time. Client Components can participate in prerendering, and MSAL's browser APIs need a browser environment.
The client is therefore created lazily:
This excerpt omits imports; the complete implementation is in msal/msal.ts.
Creating one instance is only part of startup. MSAL also has asynchronous initialization, and several callers can arrive while that work is in progress. I share the application initialization promise so those callers wait on the same bootstrap work:
The shared promise coordinates bootstrap and callback registration, including repeated development mounts. If initialization fails, I clear the promise so another attempt can retry. The client instance itself remains available.
This does not mean the SDK's initialize() method is invoked only once everywhere. The token helper also initializes defensively, and the React integration can initialize internally. The guarantee here is about my application's bootstrap work.
The active-account policy is intentionally simple: preserve the active account when one exists, otherwise select the first cached account. An application that regularly switches between accounts needs an explicit account-selection experience.
Giving redirect processing one owner
Initialization and redirect completion are separate stages.
MyMsalProvider first waits for application initialization. Once it has a client, it renders MSAL React's MsalProvider. I let that provider own redirect processing instead of adding another effect that calls handleRedirectPromise().
Microsoft's MSAL React FAQ confirms that the provider handles redirect processing internally. It also explains why work that needs the returned account or token must wait for redirect processing to finish. See the MSAL React FAQ.
Inside the provider, my authentication boundary uses inProgress and useIsAuthenticated() to decide what to show:
| State | What the sample renders |
|---|---|
| Configuration missing or malformed | Setup instructions |
| Application initialization pending | Loading status |
| Initialization failed | Generic error and reload action |
| MSAL interaction still in progress | Authentication progress status |
| MSAL idle, no authenticated account | Sign-in prompt |
| MSAL idle, authenticated account | Application content |
Waiting for InteractionStatus.None avoids deciding that the user is signed out while a redirect response is still being processed. It also keeps token and sign-in controls from acting during an unfinished interaction.
I added event handling for failed login and failed interactive token acquisition. That second case matters when someone is already signed in but declines consent for an API. They still need feedback, so the error banner can appear alongside authenticated content.
These component-level event subscriptions are removed on cleanup. The successful-login callback installed during bootstrap has the lifetime of the browser client. User-facing errors remain generic; the sample does not print raw authentication responses or tokens.
Requesting tokens silently, with explicit consent when needed
The token helper has a small policy surface:
interaction defaults to "none". A normal request tries acquireTokenSilent() and returns the access token if acquisition succeeds. When the caller explicitly permits interaction, the helper still tries silent acquisition first.
The fallback is restricted to InteractionRequiredAuthError:
This is an excerpt from msal/tokenFetcher.ts. It runs after account selection, scope validation, and construction of the request.
A failed network request should remain a failed network request. Turning every error into a new login attempt can create confusing redirects and hide the original problem. I also avoid clearing the account cache as a general recovery mechanism.
On /gettokentest, the user first requests a token through a button. If interaction is required, the page offers an explicit consent action using redirect acquisition. The controls run under the provider after MSAL has settled.
A redirect leaves the current document. The original function call does not resume with a usable token after the browser returns. Once redirect processing finishes, the page can request the token again.
The demo reports whether acquisition succeeded. It does not display the access token or write it to the console, and it does not call a custom API. Successful token acquisition therefore demonstrates only that acquisition worked, not that an API has authorized an operation.
Sharing concurrent token requests without mixing identities
Several components can ask for the same token at nearly the same time. I wanted those callers to share pending work, while keeping different accounts and resources separate.
The helper maintains a WeakMap keyed by MSAL instance. Each instance has a map of pending token promises. Before creating a key, it trims scopes, removes empty entries and duplicates, and sorts the result.
The key contains:
If a matching request is already in progress, another caller waits for that work. A request for another account, another scope set, or another interaction policy gets its own entry.
Including the interaction policy is intentional. A caller that requested silent-only behavior should not inherit another caller's permission to open a popup or redirect the page.
Each pending entry is removed in finally, whether the request succeeds or fails. A rejected request must not leave a rejected promise permanently attached to that key and make every later attempt fail immediately.
This map deduplicates in-flight work. MSAL still owns the token cache, token expiry handling, and renewal behavior. I do not maintain a second cache of completed token strings.
Resource boundaries remain important here. The custom API scope and Microsoft Graph's User.Read scope serve different resources. A Graph access token is not a general-purpose token for my API. The receiving API validates the token intended for its audience; the browser treats access tokens as opaque credentials. Microsoft documents token ownership and validation responsibilities.
Preventing overlapping interactive operations
Pending token requests and interactive operations need different coordination.
The request map allows independent silent requests to proceed. Login, logout, and consent flows also share a small interaction guard:
This is the guard's structure with shortened error wording. The complete helper is in msal/interaction.ts.
It rejects a competing operation; it does not queue it. The finally block releases the guard after failures as well as successful completion.
The buttons add two more checks: MSAL's interaction status and an immediate useRef guard against repeated clicks. A ref can block a second click before a state update has rendered the disabled button.
These checks complement MSAL's own interaction handling. Microsoft documents interaction_in_progress as a failure that can occur when another interactive request starts before an existing one has completed. See the MSAL Browser error reference.
The guard is local to this module in the current browser context. It does not coordinate browser tabs, and direct SDK calls that bypass these helpers do not participate in it. Waiting for the provider to become idle remains necessary.
Making role checks predictable
The role wrapper reads the current account through useAccount() and extracts string values from its ID token's roles claim. Missing claims or malformed values produce no roles.
I derive the rendering decision directly:
The default any mode accepts at least one matching role. The all mode requires every specified role. An empty requirement list denies access explicitly, avoiding the behavior where every() returns true for an empty array.
Blank requirements are filtered out, but meaningful role values are matched exactly, including case. I do not silently rewrite role names.
Deriving this value also removes a subtle problem from the older approach: updating an authorization flag repeatedly while iterating through roles can make the final result depend on the last role checked. some() and every() state the intended rule directly, without storing a second copy of derived state.
For example, the wrapper can express a UI requirement like this:
AdminTools here is an illustrative component, not an additional component shipped in the sample.
The full implementation is in components/UserRolesContainer.tsx. It controls presentation. The API must independently validate the access token's signature, issuer, audience, expiry, and required scopes or roles before allowing an operation.
The roles used for this UI come from the SPA's ID token. API permissions and API app roles need to be configured and enforced for the API resource. I would not assume that assigning a UI role automatically establishes an API authorization policy.
Loading the Graph avatar without disrupting authentication
The avatar is a useful example of an optional feature that should fail quietly.
The helper acquires a Graph token silently for User.Read and requests:
This uses a separate Graph token request rather than the custom API token. The Graph helper does not go through the custom token helper's pending-request map. Also, the initial sign-in request already includes User.Read; this sample does not defer all Graph consent until the avatar loads.
Microsoft Graph returns image bytes for a successful photo request and 404 when no photo exists. The profile photo API reference describes those responses.
My helper checks the response status, requires an image content type, and rejects an empty blob. Missing photos, unavailable consent, network failures, and cancellation return null, allowing the component to show initials. Loading an avatar never starts an interactive login or consent flow.
There are two cleanup responsibilities in components/UserAvatar.tsx:
- Abort the Graph fetch when the component is disposed or the account changes.
- Revoke the object URL created for the image blob.
The component also revokes a late result that arrives after disposal and associates the displayed photo with the account ID. An image decoding failure falls back to initials too.
The abort signal applies to the fetch. It does not cancel MSAL's token acquisition itself, so the helper checks cancellation again after awaiting the token. This keeps late asynchronous work from updating an obsolete avatar without claiming that every underlying operation is cancellable.
What changed in the Next.js migration
Most of the authentication work concerns lifecycle and policy. The framework migration also needed explicit maintenance around the development tools.
I moved linting to the ESLint CLI with a flat configuration:
Next.js 16 removed next lint, and next build no longer runs linting. Keeping lint and type checking as explicit checks makes the validation process clear. The Next.js 16 upgrade guide covers these changes.
The repository's .nvmrc selects Node.js 22, and the declared engine range requires at least 22.12 within that major. I also removed the external font download from the build path and set the Turbopack root explicitly for the checkout.
During verification, the local execution sandbox blocked a port-binding operation needed by a Turbopack CSS worker. The production build passed with npm run build -- --webpack. I am recording that distinction because the successful Webpack build does not establish that the default Turbopack build passed in that environment.
The behavior I verified
The checked-in Vitest suite has 39 passing cases across six test files. The tests use mock MSAL methods, synthetic accounts, and mocked Graph responses.
The most useful cases exercise boundaries that are easy to miss during a manual sign-in:
| Area | Behavior covered |
|---|---|
| Initialization | Lazy browser client, shared bootstrap, retry after failure, active-account selection |
| Token requests | Concurrent deduplication, separate accounts and scopes, separate interaction policies, cleanup after failure |
| Error handling | Silent-only default, no interactive fallback for generic network failures |
| Interaction guard | Reject overlapping operations and release the guard after failure |
| Role rendering | Any/all behavior, role order, empty requirements, missing account |
| Claims and photos | Malformed claims, initials, image response checks, unavailable photos, cancellation |
Lint, TypeScript checking, and the Webpack production build also passed.
Browser checks covered all three routes on desktop and mobile widths. The unconfigured build rendered its setup experience without runtime errors or horizontal overflow. With synthetic configuration, checks verified the sign-in UI, intercepted an authorization redirect containing PKCE parameters, and exercised a simulated denied callback to check the error message.
Those checks stopped short of a real Entra authentication round trip. They did not verify live tenant policy, MFA, consent, real Graph access, or authorization by a custom API. The avatar component's object URL cleanup is implemented, but the current unit suite does not directly test that cleanup through a mounted component.
For an actual deployment, I would still test those flows with the target app registration and API. Tenant configuration is part of the integration, and mocked SDK behavior cannot establish that it is correct.
Running the sample
The local setup starts with the repository and its lockfile:
If Node.js 22 is not installed through nvm yet, run nvm install first. Use a release that satisfies the package's engine requirement.
Then configure a Microsoft Entra app registration for this tenant-specific SPA:
- Register
http://localhost:3000/as a Single-page application redirect URI. - Put the application's client ID and directory tenant ID into the corresponding public settings in
.env.local. - Configure delegated Graph
User.Readpermission for the profile feature, with consent handled according to the tenant's policy. - To use the API token demo, expose or select a delegated scope on the intended API resource, grant the SPA permission to request it, and set the public API scope setting.
- To exercise the administrator UI, configure and assign the SPA app role represented by
Sample.Admin, or set the role value to match the one configured for the sample. Sign in again to obtain updated claims after assignment changes.
Start the app with:
The API scope and role setup are optional for basic sign-in. Leaving the required client and tenant settings empty shows the setup screen instead.
After changing the implementation, the repository's checks are:
Use the Webpack command described above when reproducing my successful production-build check in the same restricted environment. Test the chosen production build and the configured authentication flow before deployment.
What I want this repository to make easier
I want someone reading this sample to be able to follow the whole browser authentication lifecycle: where the client is created, who processes redirects, which requests can interact with the user, and how account and resource boundaries are preserved.
There are deliberate extension points. An account picker would replace the first-cached-account policy. Private server rendering would require server-side session and authorization work. More complex tenant or cloud support would change the authority and redirect configuration. A real API would add its own token validation and permission checks.
The updated nextjs-msal-app-router repository gives those decisions a smaller, readable starting point. I plan to keep the framework version in the documentation and package manifest, while the repository name stays focused on the integration itself.
