@chemmangat/msal-next 4.0.1 → 4.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,36 +1,54 @@
1
1
  # Troubleshooting Guide
2
2
 
3
- Common issues and their solutions for @chemmangat/msal-next.
3
+ Common issues and solutions for @chemmangat/msal-next
4
4
 
5
- ## "createContext only works in Client Components"
5
+ ## Table of Contents
6
6
 
7
- ### Error Message
8
- ```
9
- createContext only works in Client Components. Add the "use client" directive at the top of the file to use it.
10
- ```
7
+ 1. [Common Mistakes](#common-mistakes)
8
+ 2. [Top 5 Errors](#top-5-errors)
9
+ 3. [Configuration Issues](#configuration-issues)
10
+ 4. [Authentication Flow Issues](#authentication-flow-issues)
11
+ 5. [Development Tips](#development-tips)
12
+
13
+ ---
14
+
15
+ ## Common Mistakes
11
16
 
12
- ### Solution
13
- Use `MSALProvider` instead of `MsalAuthProvider` in your layout.tsx:
17
+ ### 1. Missing 'use client' Directive
18
+
19
+ **Problem:** You get an error: "createContext only works in Client Components"
20
+
21
+ **Solution:** Always place `'use client'` at the TOP of your file, before any imports:
14
22
 
15
- **❌ Wrong:**
16
23
  ```tsx
17
- // app/layout.tsx
18
- import { MsalAuthProvider } from '@chemmangat/msal-next';
24
+ // ✅ CORRECT
25
+ 'use client';
19
26
 
20
- export default function RootLayout({ children }) {
21
- return (
22
- <html>
23
- <body>
24
- <MsalAuthProvider clientId="...">
25
- {children}
26
- </MsalAuthProvider>
27
- </body>
28
- </html>
29
- );
27
+ import { useMsalAuth } from '@chemmangat/msal-next';
28
+
29
+ export default function MyComponent() {
30
+ const { isAuthenticated } = useMsalAuth();
31
+ // ...
30
32
  }
31
33
  ```
32
34
 
33
- **✅ Correct:**
35
+ ```tsx
36
+ // ❌ WRONG - 'use client' must be FIRST
37
+ import { useMsalAuth } from '@chemmangat/msal-next';
38
+
39
+ 'use client'; // Too late!
40
+
41
+ export default function MyComponent() {
42
+ // ...
43
+ }
44
+ ```
45
+
46
+ ### 2. Using MsalAuthProvider Instead of MSALProvider
47
+
48
+ **Problem:** Error in server-side layout.tsx
49
+
50
+ **Solution:** Use `MSALProvider` (not `MsalAuthProvider`) in your layout.tsx:
51
+
34
52
  ```tsx
35
53
  // app/layout.tsx
36
54
  import { MSALProvider } from '@chemmangat/msal-next';
@@ -39,7 +57,7 @@ export default function RootLayout({ children }) {
39
57
  return (
40
58
  <html>
41
59
  <body>
42
- <MSALProvider
60
+ <MSALProvider
43
61
  clientId={process.env.NEXT_PUBLIC_AZURE_AD_CLIENT_ID!}
44
62
  tenantId={process.env.NEXT_PUBLIC_AZURE_AD_TENANT_ID!}
45
63
  >
@@ -51,244 +69,418 @@ export default function RootLayout({ children }) {
51
69
  }
52
70
  ```
53
71
 
54
- ### Why?
55
- - Next.js App Router layouts are Server Components by default
56
- - `MsalAuthProvider` uses React Context, which requires client-side rendering
57
- - `MSALProvider` is a pre-configured wrapper that's already marked as `'use client'`
72
+ ### 3. Missing Environment Variables
58
73
 
59
- ---
74
+ **Problem:** Authentication fails silently or with cryptic errors
75
+
76
+ **Solution:** Create `.env.local` with required variables:
77
+
78
+ ```bash
79
+ # .env.local
80
+ NEXT_PUBLIC_AZURE_AD_CLIENT_ID=12345678-1234-1234-1234-123456789012
81
+ NEXT_PUBLIC_AZURE_AD_TENANT_ID=87654321-4321-4321-4321-210987654321
82
+ ```
83
+
84
+ **Important:**
85
+ - Variables must start with `NEXT_PUBLIC_` to be accessible in the browser
86
+ - Restart your dev server after adding/changing environment variables
87
+ - Never commit `.env.local` to version control
88
+
89
+ ### 4. Placeholder Values in Configuration
90
+
91
+ **Problem:** Authentication fails with "invalid client" error
60
92
 
61
- ## "no_token_request_cache_error"
93
+ **Solution:** Replace placeholder values with actual IDs from Azure Portal:
62
94
 
63
- ### Error Message
95
+ ```tsx
96
+ // ❌ WRONG - Placeholder values
97
+ <MSALProvider
98
+ clientId="your-client-id-here"
99
+ tenantId="your-tenant-id-here"
100
+ >
101
+
102
+ // ✅ CORRECT - Actual GUIDs from Azure Portal
103
+ <MSALProvider
104
+ clientId="12345678-1234-1234-1234-123456789012"
105
+ tenantId="87654321-4321-4321-4321-210987654321"
106
+ >
64
107
  ```
65
- BrowserAuthError: no_token_request_cache_error
108
+
109
+ ### 5. HTTP in Production
110
+
111
+ **Problem:** Authentication fails in production with redirect URI error
112
+
113
+ **Solution:** Always use HTTPS in production:
114
+
115
+ ```tsx
116
+ // ❌ WRONG - HTTP in production
117
+ redirectUri: "http://myapp.com"
118
+
119
+ // ✅ CORRECT - HTTPS in production
120
+ redirectUri: "https://myapp.com"
121
+
122
+ // ✅ CORRECT - HTTP only for localhost
123
+ redirectUri: "http://localhost:3000"
66
124
  ```
67
125
 
68
- ### Solution
69
- This error is now handled automatically in v3.0.2+. If you're still seeing it:
126
+ ---
70
127
 
71
- 1. **Update to the latest version:**
72
- ```bash
73
- npm install @chemmangat/msal-next@latest
74
- ```
128
+ ## Top 5 Errors
75
129
 
76
- 2. **Clear your browser cache and cookies** for your app's domain
130
+ ### Error 1: AADSTS50011 - Redirect URI Mismatch
77
131
 
78
- 3. **Ensure you're using the correct redirect URI** in Azure AD:
132
+ **Error Message:**
133
+ ```
134
+ AADSTS50011: The redirect URI 'http://localhost:3000' specified in the request does not match the redirect URIs configured for the application.
135
+ ```
136
+
137
+ **What it means:** Your app is trying to redirect to a URL that's not registered in Azure AD.
138
+
139
+ **How to fix:**
140
+
141
+ 1. Go to [Azure Portal](https://portal.azure.com)
142
+ 2. Navigate to: Azure Active Directory → App registrations → Your app
143
+ 3. Click "Authentication" in the left sidebar
144
+ 4. Under "Single-page application", click "Add URI"
145
+ 5. Add your redirect URI:
79
146
  - Development: `http://localhost:3000`
80
147
  - Production: `https://yourdomain.com`
148
+ 6. Click "Save"
81
149
 
82
- ### Why?
83
- This error occurs when:
84
- - User refreshes the page during authentication flow
85
- - There's a mismatch between cached auth state and current request
86
- - The package now handles this gracefully (v3.0.2+)
150
+ **Pro tip:** You can add multiple redirect URIs for different environments.
87
151
 
88
152
  ---
89
153
 
90
- ## "User cancelled" or Popup Closed
154
+ ### Error 2: AADSTS65001 - Admin Consent Required
91
155
 
92
- ### Error Message
156
+ **Error Message:**
93
157
  ```
94
- user_cancelled: User cancelled the flow
158
+ AADSTS65001: The user or administrator has not consented to use the application.
95
159
  ```
96
160
 
97
- ### Solution
98
- This is expected behavior when users close the popup. The package handles this gracefully.
161
+ **What it means:** Your app requires permissions that need admin approval.
99
162
 
100
- If you want to show a message to users:
163
+ **How to fix:**
101
164
 
102
- ```tsx
103
- <MicrosoftSignInButton
104
- onError={(error) => {
105
- if (error.message.includes('user_cancelled')) {
106
- console.log('User closed the login popup');
107
- // Show a friendly message
108
- }
109
- }}
110
- />
165
+ **Option 1: Grant admin consent (if you're an admin)**
166
+ 1. Go to Azure Portal → App registrations → Your app
167
+ 2. Click "API permissions"
168
+ 3. Click "Grant admin consent for [Your Organization]"
169
+ 4. Confirm the consent
170
+
171
+ **Option 2: Request admin consent (if you're not an admin)**
172
+ 1. Contact your Azure AD administrator
173
+ 2. Ask them to grant consent for your app
174
+ 3. Provide them with your Application (client) ID
175
+
176
+ **Option 3: Use delegated permissions**
177
+ - Change your app to use delegated permissions instead of application permissions
178
+ - Delegated permissions don't require admin consent
179
+
180
+ ---
181
+
182
+ ### Error 3: Missing Environment Variables
183
+
184
+ **Error Message:**
185
+ ```
186
+ NEXT_PUBLIC_AZURE_AD_CLIENT_ID not found
111
187
  ```
112
188
 
189
+ **What it means:** Required environment variables are not set.
190
+
191
+ **How to fix:**
192
+
193
+ 1. Create `.env.local` in your project root:
194
+
195
+ ```bash
196
+ # .env.local
197
+ NEXT_PUBLIC_AZURE_AD_CLIENT_ID=your-client-id
198
+ NEXT_PUBLIC_AZURE_AD_TENANT_ID=your-tenant-id
199
+ ```
200
+
201
+ 2. Get your IDs from Azure Portal:
202
+ - Client ID: App registrations → Your app → Overview → Application (client) ID
203
+ - Tenant ID: Azure Active Directory → Properties → Tenant ID
204
+
205
+ 3. Restart your development server:
206
+ ```bash
207
+ npm run dev
208
+ ```
209
+
210
+ **Important:** Never commit `.env.local` to Git!
211
+
113
212
  ---
114
213
 
115
- ## Environment Variables Not Working
214
+ ### Error 4: AADSTS700016 - Invalid Client
215
+
216
+ **Error Message:**
217
+ ```
218
+ AADSTS700016: Application with identifier 'xxx' was not found in the directory.
219
+ ```
220
+
221
+ **What it means:** The client ID is incorrect or the app doesn't exist.
116
222
 
117
- ### Symptoms
118
- - `undefined` values for clientId or tenantId
119
- - Authentication not initializing
223
+ **How to fix:**
120
224
 
121
- ### Solution
225
+ 1. Verify your client ID in Azure Portal:
226
+ - Go to App registrations → Your app
227
+ - Copy the "Application (client) ID" from the Overview page
122
228
 
123
- 1. **Check your .env.local file exists:**
124
- ```bash
125
- # .env.local
126
- NEXT_PUBLIC_AZURE_AD_CLIENT_ID=your-client-id
127
- NEXT_PUBLIC_AZURE_AD_TENANT_ID=your-tenant-id
128
- ```
229
+ 2. Update your `.env.local`:
230
+ ```bash
231
+ NEXT_PUBLIC_AZURE_AD_CLIENT_ID=correct-client-id-here
232
+ ```
129
233
 
130
- 2. **Restart your dev server** after adding environment variables:
131
- ```bash
132
- # Stop the server (Ctrl+C)
133
- npm run dev
134
- ```
234
+ 3. Ensure the format is a GUID:
235
+ - Correct: `12345678-1234-1234-1234-123456789012`
236
+ - Wrong: `my-app-name` or `12345`
135
237
 
136
- 3. **Verify the variables are prefixed with `NEXT_PUBLIC_`:**
137
- - ✅ `NEXT_PUBLIC_AZURE_AD_CLIENT_ID`
138
- - ❌ `AZURE_AD_CLIENT_ID` (won't work in client components)
238
+ 4. Restart your dev server
139
239
 
140
240
  ---
141
241
 
142
- ## "Interaction already in progress"
242
+ ### Error 5: AADSTS90002 - Invalid Tenant
143
243
 
144
- ### Error Message
244
+ **Error Message:**
145
245
  ```
146
- Interaction already in progress
246
+ AADSTS90002: Tenant 'xxx' not found.
147
247
  ```
148
248
 
149
- ### Solution
150
- This is a safety feature to prevent multiple concurrent login attempts. Wait for the current interaction to complete.
249
+ **What it means:** The tenant ID is incorrect or you're using the wrong authority type.
151
250
 
152
- The package automatically prevents this in v3.0.2+, but if you're manually calling login methods:
251
+ **How to fix:**
153
252
 
253
+ **Option 1: Fix tenant ID (for single-tenant apps)**
154
254
  ```tsx
155
- const { loginPopup, inProgress } = useMsalAuth();
156
-
157
- const handleLogin = async () => {
158
- // Check if interaction is in progress
159
- if (inProgress) {
160
- console.log('Please wait for current login to complete');
161
- return;
162
- }
163
-
164
- await loginPopup();
165
- };
255
+ <MSALProvider
256
+ clientId="your-client-id"
257
+ tenantId="correct-tenant-id" // Get from Azure Portal
258
+ authorityType="tenant"
259
+ >
260
+ ```
261
+
262
+ **Option 2: Use multi-tenant (for apps supporting any Azure AD)**
263
+ ```tsx
264
+ <MSALProvider
265
+ clientId="your-client-id"
266
+ authorityType="common" // No tenantId needed
267
+ >
268
+ ```
269
+
270
+ **Option 3: Organizations only (any organizational Azure AD)**
271
+ ```tsx
272
+ <MSALProvider
273
+ clientId="your-client-id"
274
+ authorityType="organizations" // No tenantId needed
275
+ >
166
276
  ```
167
277
 
168
278
  ---
169
279
 
170
- ## Token Acquisition Fails
280
+ ## Configuration Issues
281
+
282
+ ### Issue: Configuration Validation Warnings
283
+
284
+ **Problem:** You see warnings in the console about configuration issues.
171
285
 
172
- ### Symptoms
173
- - `acquireToken()` throws errors
174
- - Silent token acquisition fails
286
+ **Solution:** The package includes automatic configuration validation in development mode. Follow the fix instructions in the console output.
175
287
 
176
- ### Solution
288
+ **Example warning:**
289
+ ```
290
+ ⚠️ Warnings (should fix)
177
291
 
178
- 1. **Ensure user is logged in:**
179
- ```tsx
180
- const { isAuthenticated, acquireToken } = useMsalAuth();
181
-
182
- if (!isAuthenticated) {
183
- // User needs to login first
184
- await loginPopup();
185
- }
186
-
187
- const token = await acquireToken(['User.Read']);
188
- ```
292
+ clientId:
293
+ Client ID appears to be a placeholder
189
294
 
190
- 2. **Check the scopes are granted in Azure AD:**
191
- - Go to Azure Portal App Registrations Your App → API Permissions
192
- - Ensure the scopes you're requesting are listed and granted
295
+ Fix:
296
+ Replace the placeholder with your actual Application (client) ID from Azure Portal.
297
+ ```
193
298
 
194
- 3. **Use the fallback pattern:**
195
- ```tsx
196
- // acquireToken automatically falls back to popup if silent fails
197
- const token = await acquireToken(['User.Read']);
198
- ```
299
+ **How to fix:** Follow the instructions in the warning message.
199
300
 
200
301
  ---
201
302
 
202
- ## Build Errors with package.json
303
+ ### Issue: Cookies Not Working
203
304
 
204
- ### Error Message
205
- ```
206
- Error parsing package.json file
305
+ **Problem:** Authentication state is lost on page refresh.
306
+
307
+ **Solution:** Ensure cookies are enabled and not blocked:
308
+
309
+ 1. Check browser settings - cookies must be enabled
310
+ 2. Check for browser extensions blocking cookies
311
+ 3. In production, ensure your domain is properly configured
312
+ 4. For localhost, ensure you're using `http://localhost:3000` (not `127.0.0.1`)
313
+
314
+ ---
315
+
316
+ ## Authentication Flow Issues
317
+
318
+ ### Issue: Infinite Redirect Loop
319
+
320
+ **Problem:** Page keeps redirecting back and forth.
321
+
322
+ **Solution:**
323
+
324
+ 1. Check your middleware configuration:
325
+ ```tsx
326
+ // middleware.ts
327
+ export const middleware = createAuthMiddleware({
328
+ protectedRoutes: ['/dashboard'],
329
+ publicOnlyRoutes: ['/login'], // Don't protect login page!
330
+ loginPath: '/login',
331
+ });
207
332
  ```
208
333
 
209
- ### Solution
210
- This was fixed in v3.0.1. Update to the latest version:
334
+ 2. Ensure login page is not protected
335
+ 3. Clear browser cache and cookies
336
+ 4. Check for conflicting middleware
211
337
 
212
- ```bash
213
- npm install @chemmangat/msal-next@latest
338
+ ---
339
+
340
+ ### Issue: Token Acquisition Fails
341
+
342
+ **Problem:** `acquireToken()` throws an error.
343
+
344
+ **Solution:**
345
+
346
+ 1. Ensure user is logged in:
347
+ ```tsx
348
+ const { isAuthenticated, acquireToken } = useMsalAuth();
349
+
350
+ if (!isAuthenticated) {
351
+ // User must login first
352
+ await loginRedirect();
353
+ return;
354
+ }
355
+
356
+ const token = await acquireToken(['User.Read']);
214
357
  ```
215
358
 
216
- If you're still having issues:
217
- 1. Delete `node_modules` and `package-lock.json`
218
- 2. Run `npm install` again
219
- 3. Clear Next.js cache: `rm -rf .next`
359
+ 2. Check that scopes are granted in Azure Portal:
360
+ - Go to API permissions
361
+ - Ensure required scopes are added
362
+ - Grant admin consent if needed
363
+
364
+ 3. Use correct scope format:
365
+ - Correct: `User.Read`, `Mail.Read`
366
+ - Wrong: `user.read`, `read_mail`
220
367
 
221
368
  ---
222
369
 
223
- ## TypeScript Errors
370
+ ## Development Tips
371
+
372
+ ### Enable Debug Logging
373
+
374
+ Get detailed logs to troubleshoot issues:
375
+
376
+ ```tsx
377
+ <MSALProvider
378
+ clientId="your-client-id"
379
+ enableLogging={true} // Enable debug logs
380
+ >
381
+ {children}
382
+ </MSALProvider>
383
+ ```
384
+
385
+ ### Use the Enhanced Debug Logger
386
+
387
+ For more detailed logging:
388
+
389
+ ```tsx
390
+ import { getDebugLogger } from '@chemmangat/msal-next';
391
+
392
+ const logger = getDebugLogger({
393
+ enabled: true,
394
+ enablePerformance: true,
395
+ enableNetworkLogs: true,
396
+ });
397
+
398
+ // Track performance
399
+ logger.startTiming('token-acquisition');
400
+ const token = await acquireToken(['User.Read']);
401
+ logger.endTiming('token-acquisition');
402
+
403
+ // Export logs for debugging
404
+ logger.downloadLogs('debug-logs.json');
405
+ ```
406
+
407
+ ### Check MSAL Instance
224
408
 
225
- ### Symptoms
226
- - Type errors with MSAL types
227
- - Missing type definitions
409
+ Access the MSAL instance for debugging:
228
410
 
229
- ### Solution
411
+ ```tsx
412
+ import { getMsalInstance } from '@chemmangat/msal-next';
413
+
414
+ const instance = getMsalInstance();
415
+ console.log('Accounts:', instance?.getAllAccounts());
416
+ console.log('Active account:', instance?.getActiveAccount());
417
+ ```
418
+
419
+ ### Test in Incognito Mode
420
+
421
+ Many auth issues are caused by cached state. Test in incognito/private mode to rule out cache issues.
230
422
 
231
- 1. **Ensure peer dependencies are installed:**
232
- ```bash
233
- npm install @azure/msal-browser@^4.0.0 @azure/msal-react@^3.0.0
234
- ```
423
+ ### Clear MSAL Cache
235
424
 
236
- 2. **Check your tsconfig.json includes:**
237
- ```json
238
- {
239
- "compilerOptions": {
240
- "moduleResolution": "bundler",
241
- "jsx": "preserve",
242
- "lib": ["dom", "dom.iterable", "esnext"]
243
- }
244
- }
245
- ```
425
+ If you're experiencing persistent issues:
426
+
427
+ ```tsx
428
+ const { clearSession } = useMsalAuth();
429
+
430
+ // Clear MSAL cache without logging out from Microsoft
431
+ await clearSession();
432
+ ```
246
433
 
247
434
  ---
248
435
 
249
436
  ## Still Having Issues?
250
437
 
251
- 1. **Enable debug logging:**
252
- ```tsx
253
- <MSALProvider
254
- clientId="..."
255
- enableLogging={true}
256
- >
257
- {children}
258
- </MSALProvider>
259
- ```
438
+ 1. **Check the documentation:** [README.md](./README.md)
439
+ 2. **Search existing issues:** [GitHub Issues](https://github.com/chemmangat/msal-next/issues)
440
+ 3. **Ask for help:** [GitHub Discussions](https://github.com/chemmangat/msal-next/discussions)
441
+ 4. **Report a bug:** [New Issue](https://github.com/chemmangat/msal-next/issues/new)
442
+
443
+ When reporting issues, please include:
444
+ - Package version
445
+ - Next.js version
446
+ - Node.js version
447
+ - Error messages (full stack trace)
448
+ - Minimal reproduction code
449
+ - Steps to reproduce
450
+
451
+ ---
452
+
453
+ ## Quick Reference
454
+
455
+ ### Get Azure AD IDs
456
+
457
+ 1. **Client ID:**
458
+ - Azure Portal → App registrations → Your app → Overview
459
+ - Copy "Application (client) ID"
460
+
461
+ 2. **Tenant ID:**
462
+ - Azure Portal → Azure Active Directory → Properties
463
+ - Copy "Tenant ID"
464
+
465
+ ### Add Redirect URI
260
466
 
261
- 2. **Check the browser console** for detailed error messages
467
+ 1. Azure Portal App registrations Your app
468
+ 2. Click "Authentication"
469
+ 3. Under "Single-page application", click "Add URI"
470
+ 4. Enter your URI (e.g., `http://localhost:3000`)
471
+ 5. Click "Save"
262
472
 
263
- 3. **Verify Azure AD configuration:**
264
- - Redirect URIs are correct
265
- - App is not expired
266
- - Required permissions are granted
473
+ ### Grant API Permissions
267
474
 
268
- 4. **Open an issue on GitHub:**
269
- - Include error messages
270
- - Include relevant code snippets
271
- - Include package versions: `npm list @chemmangat/msal-next`
475
+ 1. Azure Portal App registrations → Your app
476
+ 2. Click "API permissions"
477
+ 3. Click "Add a permission"
478
+ 4. Select "Microsoft Graph"
479
+ 5. Select "Delegated permissions"
480
+ 6. Search and select permissions (e.g., "User.Read")
481
+ 7. Click "Add permissions"
482
+ 8. Click "Grant admin consent" (if required)
272
483
 
273
484
  ---
274
485
 
275
- ## Common Azure AD Configuration Issues
276
-
277
- ### Redirect URI Mismatch
278
- - **Error:** `redirect_uri_mismatch`
279
- - **Solution:** Add your app's URL to Azure AD → App Registrations → Authentication → Redirect URIs
280
-
281
- ### Missing Permissions
282
- - **Error:** `consent_required` or `invalid_grant`
283
- - **Solution:** Add required API permissions in Azure AD and grant admin consent if needed
284
-
285
- ### Multi-tenant Issues
286
- - **Solution:** Use `authorityType: "common"` for multi-tenant apps:
287
- ```tsx
288
- <MSALProvider
289
- clientId="..."
290
- authorityType="common"
291
- >
292
- {children}
293
- </MSALProvider>
294
- ```
486
+ **Last updated:** v4.0.2