Authentication in Single Page Applications is usually straightforward: initialize your authentication library, redirect the user to sign in, and store the resulting tokens.
With Nuxt 4, however, things become more interesting.
Nuxt is not just a client-side framework. It is an SSR (Server-Side Rendering) framework, which means your code can execute on both the server and the browser. If you treat authentication the same way you would in a Vue SPA, you’ll quickly run into issues such as:
window is not definedlocalStorage is not definednon_browser_environment- MSAL initialization failures
- Authentication state not being available during SSR
This article walks through a production-ready approach for implementing both authentication and authorization in a Nuxt 4 application using Azure MSAL, while ensuring your server-side APIs are protected as well.
Originally published on Medium.
Understanding the SSR Challenge
One of the most common misconceptions when starting with Nuxt is assuming that all application code runs in the browser.
In reality, Nuxt renders pages on the server first and then hydrates them on the client.
The lifecycle looks something like this:
Browser Request
↓
Nuxt Server
↓
Page Rendered on Server
↓
HTML Sent to Browser
↓
Client Hydration
↓
Browser-Specific Code Executes
The Azure MSAL Browser SDK (@azure/msal-browser) depends heavily on browser APIs such as:
windowlocalStoragesessionStorage- redirects
These APIs do not exist during SSR.
If MSAL initialization happens anywhere that Nuxt attempts to execute on the server, authentication will fail before the application even reaches the browser.
The solution is to ensure that MSAL is initialized exclusively on the client side.

Creating a Client-Side MSAL Plugin
Nuxt plugins provide an excellent mechanism for creating shared services.
Because MSAL must never run on the server, we create a client-only plugin:
app/
└── plugins/
└── msal.client.ts
The .client.ts suffix guarantees that Nuxt only loads this file in the browser.
The plugin creates and initializes a single PublicClientApplication instance:
import { PublicClientApplication } from '@azure/msal-browser'
export default defineNuxtPlugin(async () => {
const auth = getMSALEnvironment()
const msalConfig = {
auth,
cache: {
cacheLocation: 'localStorage',
},
}
const msalInstance = new PublicClientApplication(msalConfig)
await msalInstance.initialize()
return {
provide: {
msal: msalInstance,
},
}
})
By returning the instance through provide, it becomes accessible anywhere in the application through:
const { $msal } = useNuxtApp()
This creates a single source of truth for authentication across the application.
Encapsulating Authentication Logic in a Composable
Authentication logic tends to spread across components very quickly.
A better pattern is to centralize everything into a composable.
app/
└── composables/
└── authentication.ts
This composable becomes responsible for:
- Sign-in
- Sign-out
- Account selection
- Token acquisition
- User profile management
- Redirect handling
Instead of every component directly interacting with MSAL, they simply consume:
const {
signIn,
logOut,
getAccessToken,
} = await useAuth()
This separation significantly improves maintainability and testability.
Handling Redirect Responses Correctly
One of the most frequent MSAL mistakes is forgetting to process redirect responses.
After Azure AD redirects users back to your application, MSAL stores authentication information that must be processed.
In Nuxt, a global route middleware is an excellent place for this logic.
app/
└── middleware/
└── auth.global.ts
Example:
export default defineNuxtRouteMiddleware(async () => {
if (!import.meta.client) {
return
}
const { initializeAuth, handleMSALResponse } = await useAuth()
const msal = initializeAuth()
try {
const response = await msal.handleRedirectPromise()
handleMSALResponse(response)
}
catch (error) {
handleMSALResponse(null)
}
})
Notice the critical guard:
if (!import.meta.client) {
return
}
Without this check, Nuxt would attempt to execute redirect handling during SSR.
Authentication vs Authorization
Many applications stop after user authentication.
This is a serious mistake.
Authentication answers:
Who is the user?
Authorization answers:
Is the user allowed to access this resource?
A user successfully logging into Azure AD does not automatically mean your server APIs are protected.
Every server endpoint must validate incoming tokens independently.
Never trust authentication performed solely on the client.
Creating an API Scope in Azure App Registration
To authorize requests against your backend APIs, Azure AD must issue an access token intended for your application.
Navigate to:
Azure Portal
→ App Registrations
→ Expose an API
Create a scope such as:
access_as_user
Azure generates an identifier similar to:
api://<client-id>/access_as_user
This scope tells Azure AD:
Issue a token that this backend API can validate.
Requesting API Tokens from the Client
When calling backend APIs, the client should request the custom API scope instead of Microsoft Graph scopes.
Example:
const tokenRequest = {
scopes: [`api://${clientId}/access_as_user`],
account,
}
const response = await $msal.acquireTokenSilent(tokenRequest)
return response.accessToken
This produces an access token whose audience is your application rather than Microsoft Graph.
That distinction is important.
A Graph token should not be accepted by your backend.
Your backend should only accept tokens specifically issued for your API. Now you can use this token for calling your Nuxt server—the best way I believe is creating an Axios instance and then adding a request interceptor that fetches the token from authentication.ts and attaches it to the request header.
Securing Nuxt Server Routes
Once authentication works on the client, we need to protect server endpoints.
A clean approach is creating a server middleware:
server/
└── middleware/
└── auth.ts
The middleware intercepts incoming requests before route handlers execute.
We only want protection for backend APIs:
if (
baseUrl.startsWith('/api')
&& baseUrl !== '/api/health'
&& baseUrl !== '/api/prometheus'
)
This keeps public endpoints accessible while protecting application APIs.
Why Not Trust the Token Blindly?
An access token is simply a JWT.
Anyone can send a JWT.
Your server must verify:
- Signature
- Issuer
- Audience
- Expiration
- Tenant
If any of these checks fail, access should be denied.
Verifying Tokens with JOSE
While @azure/msal-node can be used for server-side authentication flows and token acquisition, token validation is often simpler and more lightweight with the jose package.
The middleware uses Microsoft’s public signing keys:
import { createRemoteJWKSet, jwtVerify } from 'jose'
Create a remote JWK set:
const JWKS = createRemoteJWKSet(
new URL(
`https://login.microsoftonline.com/${tenantId}/discovery/v2.0/keys`,
),
)
Then verify the token:
await jwtVerify(token, JWKS, {
issuer: `https://login.microsoftonline.com/${tenantId}/v2.0`,
audience: clientId,
})
This ensures:
- Microsoft issued the token
- The token wasn’t modified
- The token belongs to your tenant
- The token was intended for your application
If verification fails:
setResponseStatus(event, 401)
return {
statusCode: 401,
message: 'Unauthorized access',
}
Recommended Directory Structure
app/
├── composables/
│ └── authentication.ts
│
├── middleware/
│ └── auth.global.ts
│
└── plugins/
└── msal.client.ts
server/
└── middleware/
└── auth.ts
Responsibilities:
msal.client.ts→ Initialize MSAL in browser onlyauthentication.ts→ Centralize authentication logicauth.global.ts→ Process redirects and user sessionserver/middleware/auth.ts→ Validate JWTs for API requests
Common Pitfalls
Initializing MSAL During SSR
Bad:
import { PublicClientApplication } from '@azure/msal-browser'
inside shared server-executed code.
Result:
window is not defined
Using Graph Tokens for Backend APIs
Bad:
scopes: ['user.read']
for API authorization.
Your backend should validate tokens issued specifically for your API scope.
Trusting Client Authentication
Bad:
User logged in = API access granted
Client-side authentication alone does not protect server endpoints. Your server endpoints can be accessed outside of the client, by another application or Postman/Bruno.
Skipping Audience Validation
Bad:
jwtVerify(token, JWKS)
Always validate:
- issuer
- audience
to ensure the token was intended for your application.
Final Thoughts
Implementing Azure AD authentication in Nuxt 4 requires understanding that Nuxt is not purely a browser application. The server executes code before the browser ever sees the page, and browser-specific libraries such as @azure/msal-browser must be isolated carefully.
A robust setup typically follows four principles:
- Initialize MSAL only on the client.
- Expose a single MSAL instance through a Nuxt plugin.
- Centralize authentication logic in composables and route middleware.
- Independently verify access tokens on the server before allowing API access.
When both client-side authentication and server-side authorization are implemented correctly, you gain a secure architecture where Azure AD identities are trusted, API access is validated, and Nuxt SSR works seamlessly without the common MSAL pitfalls.
Thank you for taking the time to read this article.
I hope it helped clarify the challenges of implementing authentication and authorization in a Nuxt 4 application using Azure MSAL, especially in an SSR environment. If you’ve encountered similar issues or have a different approach, I’d love to hear about your experience.
If you found this article useful, consider sharing it with other developers who are working with Nuxt, Azure AD, or enterprise authentication workflows.
Happy coding!



