@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.
package/CHANGELOG.md CHANGED
@@ -2,6 +2,158 @@
2
2
 
3
3
  All notable changes to this project will be documented in this file.
4
4
 
5
+ ## [4.0.2] - 2026-03-07
6
+
7
+ ### 🎉 Developer Experience Release - Better Types, Errors & Validation
8
+
9
+ This release focuses on making the package easier to use and debug with complete TypeScript types, actionable error messages, and automatic configuration validation.
10
+
11
+ ### ✨ New Features
12
+
13
+ #### Complete TypeScript Types
14
+ - **Extended UserProfile interface** with ALL Microsoft Graph /me endpoint fields
15
+ - Added: `department`, `preferredLanguage`, `employeeId`, `companyName`, `country`, `city`, `state`, `streetAddress`, `postalCode`, `usageLocation`, `manager`, `aboutMe`, `birthday`, `interests`, `skills`, `schools`, `pastProjects`, `responsibilities`, `mySite`, `faxNumber`, `accountEnabled`, `ageGroup`, `userType`, `employeeHireDate`, `employeeType`
16
+ - Full JSDoc comments for each field
17
+ - Generic type support: `useUserProfile<T extends UserProfile>()`
18
+ - Extensible for custom organization fields
19
+
20
+ #### Enhanced Error Handling
21
+ - **New MsalError class** that wraps MSAL errors with actionable messages
22
+ - **Automatic error detection** for common Azure AD errors:
23
+ - `AADSTS50011` (Redirect URI mismatch) → Step-by-step fix instructions
24
+ - `AADSTS65001` (Consent required) → How to grant admin consent
25
+ - `AADSTS700016` (Invalid client) → How to verify client ID
26
+ - `AADSTS90002` (Invalid tenant) → How to fix tenant configuration
27
+ - `user_cancelled` → Graceful handling (not a real error)
28
+ - `no_token_request_cache_error` → Explanation and fix
29
+ - `interaction_required` / `consent_required` → User-friendly messages
30
+ - **Colored console output** in development mode with emojis
31
+ - **Error helper methods**: `isUserCancellation()`, `requiresInteraction()`
32
+ - **Documentation links** included in error messages
33
+
34
+ #### Development Mode Configuration Validator
35
+ - **Automatic validation** of MSAL configuration in development mode
36
+ - **Detects common mistakes**:
37
+ - Placeholder values (e.g., "your-client-id-here")
38
+ - Missing environment variables
39
+ - Invalid GUID format for client/tenant IDs
40
+ - HTTP in production (should be HTTPS)
41
+ - Invalid scope formats
42
+ - **Helpful warnings** with fix instructions and emojis (⚠️, ✓, ✗)
43
+ - **Runs once on mount** and caches results for performance
44
+ - **Zero performance impact** in production (only runs in development)
45
+
46
+ ### 📚 Documentation
47
+
48
+ #### New TROUBLESHOOTING.md
49
+ - **Common Mistakes** section with before/after examples
50
+ - **Top 5 Errors** with detailed solutions:
51
+ 1. AADSTS50011 - Redirect URI mismatch
52
+ 2. AADSTS65001 - Admin consent required
53
+ 3. Missing environment variables
54
+ 4. AADSTS700016 - Invalid client
55
+ 5. AADSTS90002 - Invalid tenant
56
+ - **Configuration Issues** troubleshooting
57
+ - **Authentication Flow Issues** solutions
58
+ - **Development Tips** for debugging
59
+ - **Quick Reference** for Azure Portal tasks
60
+
61
+ #### Updated README.md
62
+ - **All code examples** now show `'use client'` FIRST
63
+ - **"What's New in v4.0.2"** section highlighting new features
64
+ - **Common Mistakes** section added
65
+ - **TypeScript examples** updated to show complete types
66
+ - **Error handling examples** with new MsalError class
67
+ - **Configuration validation** examples
68
+
69
+ ### 🔧 Improvements
70
+
71
+ - **Better error messages** throughout the package
72
+ - **Improved logging** in development mode
73
+ - **Type safety** for all user profile fields
74
+ - **Automatic validation** prevents common configuration mistakes
75
+ - **Clearer documentation** with more examples
76
+
77
+ ### 🐛 Bug Fixes
78
+
79
+ - Fixed missing TypeScript types for user profile fields
80
+ - Improved error handling in all authentication flows
81
+ - Better detection of user cancellation vs real errors
82
+
83
+ ### 📦 Exports
84
+
85
+ New exports added:
86
+ ```typescript
87
+ // Types
88
+ export type { UserProfile, UseUserProfileReturn } from '@chemmangat/msal-next';
89
+ export type { ValidationResult, ValidationWarning, ValidationError } from '@chemmangat/msal-next';
90
+
91
+ // Error handling
92
+ export { MsalError, wrapMsalError, createMissingEnvVarError } from '@chemmangat/msal-next';
93
+
94
+ // Configuration validation
95
+ export { validateConfig, displayValidationResults } from '@chemmangat/msal-next';
96
+ ```
97
+
98
+ ### 🔄 Breaking Changes
99
+
100
+ **None!** This release is 100% backward compatible with v4.0.1.
101
+
102
+ ### 📝 Migration from v4.0.1
103
+
104
+ No code changes required! Simply update:
105
+
106
+ ```bash
107
+ npm install @chemmangat/msal-next@4.0.2
108
+ ```
109
+
110
+ **Optional improvements you can make:**
111
+
112
+ 1. **Use complete types:**
113
+ ```typescript
114
+ const { profile } = useUserProfile();
115
+ // Now has access to: department, preferredLanguage, employeeId, etc.
116
+ console.log(profile?.department);
117
+ console.log(profile?.preferredLanguage);
118
+ ```
119
+
120
+ 2. **Better error handling:**
121
+ ```typescript
122
+ import { wrapMsalError } from '@chemmangat/msal-next';
123
+
124
+ try {
125
+ await loginRedirect();
126
+ } catch (error) {
127
+ const msalError = wrapMsalError(error);
128
+ if (msalError.isUserCancellation()) {
129
+ return; // User cancelled, ignore
130
+ }
131
+ console.error(msalError.toConsoleString()); // Actionable error message
132
+ }
133
+ ```
134
+
135
+ 3. **Manual validation (optional):**
136
+ ```typescript
137
+ import { validateConfig, displayValidationResults } from '@chemmangat/msal-next';
138
+
139
+ const result = validateConfig({
140
+ clientId: process.env.NEXT_PUBLIC_AZURE_AD_CLIENT_ID!,
141
+ tenantId: process.env.NEXT_PUBLIC_AZURE_AD_TENANT_ID,
142
+ });
143
+
144
+ displayValidationResults(result);
145
+ ```
146
+
147
+ ### 🎯 What's Next
148
+
149
+ v4.1.0 will focus on:
150
+ - Additional Graph API helpers
151
+ - More authentication examples
152
+ - Performance optimizations
153
+ - Enhanced testing coverage
154
+
155
+ ---
156
+
5
157
  ## [3.1.7] - 2026-03-05
6
158
 
7
159
  ### 🔄 Breaking Change - Redirect-Only Flow
@@ -121,7 +273,7 @@ await logoutRedirect();
121
273
  ### 🚨 CRITICAL BUG FIX
122
274
 
123
275
  #### Popup Authentication Fixed
124
- **This release fixes a critical bug introduced in v3.0.6 that broke popup authentication for 650+ users.**
276
+ **This release fixes a critical bug introduced in v3.0.6 that broke popup authentication for 2,200+ users.**
125
277
 
126
278
  **Problem:** In v3.0.6, we skipped `handleRedirectPromise()` in popup windows, which prevented MSAL from completing the authentication flow. This caused popups to not close and authentication to fail.
127
279
 
package/README.md CHANGED
@@ -5,9 +5,166 @@ Production-grade MSAL authentication library for Next.js App Router with minimal
5
5
  [![npm version](https://badge.fury.io/js/@chemmangat%2Fmsal-next.svg)](https://www.npmjs.com/package/@chemmangat/msal-next)
6
6
  [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
7
7
 
8
- > **📦 Current Version: 4.0.1** - Zero-Config Protected Routes! Protect any page with one line of code.
8
+ > **📦 Current Version: 4.0.2** - Enhanced Developer Experience with Complete Types & Better Errors!
9
9
 
10
- > **🚀 What's New:** Export `auth = { required: true }` from any page to protect it. No middleware, no boilerplate!
10
+ > **🚀 What's New in v4.0.2:** Complete TypeScript types for user profiles, actionable error messages with fix instructions, and automatic configuration validation in development mode!
11
+
12
+ ## 🎉 What's New in v4.0.2
13
+
14
+ ### Complete TypeScript Types
15
+ ```tsx
16
+ const { profile } = useUserProfile();
17
+
18
+ // Now available with full type safety!
19
+ console.log(profile?.department);
20
+ console.log(profile?.preferredLanguage);
21
+ console.log(profile?.employeeId);
22
+ console.log(profile?.companyName);
23
+ console.log(profile?.country);
24
+ // ... and 20+ more fields!
25
+ ```
26
+
27
+ ### Actionable Error Messages
28
+ ```tsx
29
+ // Before: Cryptic error
30
+ Error: AADSTS50011
31
+
32
+ // After: Helpful guidance
33
+ 🚨 MSAL Authentication Error
34
+
35
+ Error: Redirect URI mismatch
36
+
37
+ 💡 How to fix:
38
+ Your redirect URI doesn't match what's configured in Azure AD.
39
+
40
+ Fix:
41
+ 1. Go to Azure Portal → Azure Active Directory → App registrations
42
+ 2. Select your app → Authentication
43
+ 3. Under "Single-page application", add your redirect URI:
44
+ • http://localhost:3000 (for development)
45
+ • https://yourdomain.com (for production)
46
+ 4. Click "Save"
47
+
48
+ 📚 Documentation: https://learn.microsoft.com/...
49
+ ```
50
+
51
+ ### Automatic Configuration Validation
52
+ ```tsx
53
+ // Development mode automatically checks for:
54
+ ⚠️ Warnings (should fix)
55
+
56
+ clientId:
57
+ Client ID appears to be a placeholder
58
+
59
+ Fix:
60
+ Replace the placeholder with your actual Application (client) ID from Azure Portal.
61
+
62
+ Current value: your-client-id-here
63
+ Expected format: 12345678-1234-1234-1234-123456789012 (GUID)
64
+ ```
65
+
66
+ ---
67
+
68
+ ## Common Mistakes (and How to Avoid Them)
69
+
70
+ ### ❌ Mistake #1: 'use client' in the wrong place
71
+
72
+ ```tsx
73
+ // WRONG - 'use client' must be FIRST
74
+ import { useMsalAuth } from '@chemmangat/msal-next';
75
+
76
+ 'use client'; // Too late!
77
+
78
+ export default function MyComponent() {
79
+ const { isAuthenticated } = useMsalAuth();
80
+ // ...
81
+ }
82
+ ```
83
+
84
+ ```tsx
85
+ // CORRECT - 'use client' comes FIRST
86
+ 'use client';
87
+
88
+ import { useMsalAuth } from '@chemmangat/msal-next';
89
+
90
+ export default function MyComponent() {
91
+ const { isAuthenticated } = useMsalAuth();
92
+ // ...
93
+ }
94
+ ```
95
+
96
+ ### ❌ Mistake #2: Using MsalAuthProvider in layout.tsx
97
+
98
+ ```tsx
99
+ // WRONG - Will cause "createContext only works in Client Components" error
100
+ import { MsalAuthProvider } from '@chemmangat/msal-next';
101
+
102
+ export default function RootLayout({ children }) {
103
+ return <MsalAuthProvider>{children}</MsalAuthProvider>;
104
+ }
105
+ ```
106
+
107
+ ```tsx
108
+ // CORRECT - Use MSALProvider instead
109
+ import { MSALProvider } from '@chemmangat/msal-next';
110
+
111
+ export default function RootLayout({ children }) {
112
+ return <MSALProvider clientId="...">{children}</MSALProvider>;
113
+ }
114
+ ```
115
+
116
+ ### ❌ Mistake #3: Placeholder values in production
117
+
118
+ ```tsx
119
+ // WRONG - Placeholder values
120
+ <MSALProvider
121
+ clientId="your-client-id-here"
122
+ tenantId="your-tenant-id-here"
123
+ >
124
+ ```
125
+
126
+ ```tsx
127
+ // CORRECT - Actual GUIDs from Azure Portal
128
+ <MSALProvider
129
+ clientId="12345678-1234-1234-1234-123456789012"
130
+ tenantId="87654321-4321-4321-4321-210987654321"
131
+ >
132
+ ```
133
+
134
+ ### ❌ Mistake #4: Missing environment variables
135
+
136
+ ```tsx
137
+ // WRONG - Hardcoded values
138
+ <MSALProvider clientId="12345678-1234-1234-1234-123456789012">
139
+ ```
140
+
141
+ ```tsx
142
+ // CORRECT - Use environment variables
143
+ <MSALProvider
144
+ clientId={process.env.NEXT_PUBLIC_AZURE_AD_CLIENT_ID!}
145
+ tenantId={process.env.NEXT_PUBLIC_AZURE_AD_TENANT_ID!}
146
+ >
147
+ ```
148
+
149
+ ```bash
150
+ # .env.local
151
+ NEXT_PUBLIC_AZURE_AD_CLIENT_ID=12345678-1234-1234-1234-123456789012
152
+ NEXT_PUBLIC_AZURE_AD_TENANT_ID=87654321-4321-4321-4321-210987654321
153
+ ```
154
+
155
+ ### ❌ Mistake #5: HTTP in production
156
+
157
+ ```tsx
158
+ // WRONG - HTTP in production
159
+ redirectUri: "http://myapp.com"
160
+
161
+ // CORRECT - HTTPS in production, HTTP only for localhost
162
+ redirectUri: process.env.NODE_ENV === 'production'
163
+ ? "https://myapp.com"
164
+ : "http://localhost:3000"
165
+ ```
166
+
167
+ ---
11
168
 
12
169
  ## 🚀 What's New in v4.0.1
13
170
 
@@ -368,7 +525,7 @@ const data = await graph.request('/me/drive', {
368
525
 
369
526
  ### useUserProfile
370
527
 
371
- Fetch and cache user profile from MS Graph.
528
+ Fetch and cache user profile from MS Graph with complete TypeScript types.
372
529
 
373
530
  ```tsx
374
531
  const { profile, loading, error, refetch } = useUserProfile();
@@ -381,10 +538,31 @@ return (
381
538
  <h1>{profile.displayName}</h1>
382
539
  <p>{profile.mail}</p>
383
540
  <p>{profile.jobTitle}</p>
541
+ <p>{profile.department}</p>
542
+ <p>{profile.preferredLanguage}</p>
543
+ <p>{profile.employeeId}</p>
544
+ <p>{profile.companyName}</p>
545
+ <p>{profile.officeLocation}</p>
384
546
  </div>
385
547
  );
386
548
  ```
387
549
 
550
+ **New in v4.0.2:** Complete TypeScript types with 30+ fields from Microsoft Graph:
551
+ - `department`, `preferredLanguage`, `employeeId`, `companyName`
552
+ - `country`, `city`, `state`, `streetAddress`, `postalCode`
553
+ - `manager`, `aboutMe`, `birthday`, `interests`, `skills`
554
+ - And many more!
555
+
556
+ **Generic type support:**
557
+ ```tsx
558
+ interface MyProfile extends UserProfile {
559
+ customField: string;
560
+ }
561
+
562
+ const { profile } = useUserProfile<MyProfile>();
563
+ console.log(profile?.customField); // Type-safe!
564
+ ```
565
+
388
566
  ### useRoles
389
567
 
390
568
  Access user's Azure AD roles and groups.
@@ -665,6 +843,17 @@ export default function AdminPage() {
665
843
  **Issue**: Middleware not protecting routes
666
844
  **Solution**: Ensure session cookies are being set after login
667
845
 
846
+ **Issue**: "createContext only works in Client Components"
847
+ **Solution**: Use `MSALProvider` (not `MsalAuthProvider`) in layout.tsx
848
+
849
+ **Issue**: Redirect URI mismatch (AADSTS50011)
850
+ **Solution**: Add your redirect URI to Azure Portal → App registrations → Authentication
851
+
852
+ **Issue**: Missing environment variables
853
+ **Solution**: Create `.env.local` with `NEXT_PUBLIC_AZURE_AD_CLIENT_ID` and `NEXT_PUBLIC_AZURE_AD_TENANT_ID`
854
+
855
+ For more detailed troubleshooting, see [TROUBLESHOOTING.md](./TROUBLESHOOTING.md)
856
+
668
857
  ### Debug Mode
669
858
 
670
859
  Enable debug logging to troubleshoot issues:
@@ -678,6 +867,33 @@ Enable debug logging to troubleshoot issues:
678
867
  </MsalAuthProvider>
679
868
  ```
680
869
 
870
+ ### Enhanced Error Handling (v4.0.2)
871
+
872
+ Use the new MsalError class for better error messages:
873
+
874
+ ```tsx
875
+ import { wrapMsalError } from '@chemmangat/msal-next';
876
+
877
+ try {
878
+ await loginRedirect();
879
+ } catch (error) {
880
+ const msalError = wrapMsalError(error);
881
+
882
+ // Check if user just cancelled (not a real error)
883
+ if (msalError.isUserCancellation()) {
884
+ return;
885
+ }
886
+
887
+ // Get actionable error message with fix instructions
888
+ console.error(msalError.toConsoleString());
889
+
890
+ // Access error details
891
+ console.log('Error code:', msalError.code);
892
+ console.log('Fix instructions:', msalError.fix);
893
+ console.log('Documentation:', msalError.docs);
894
+ }
895
+ ```
896
+
681
897
  ## Migration to v4.0.1
682
898
 
683
899
  ### From v3.x to v4.0.1