ptech-shell-react
v2.14.0
Published
Production React adapters (MSAL bootstrap, auth gate, user service, react-router navigation) for Module Federation shell apps.
Maintainers
Readme
ptech-shell-react
Production React adapters for PTECH Module Federation shell apps.
This package bridges framework/runtime libraries into the contracts exported by ptech-shell-sdk.
Exports
Root entry:
import {
createMsalUserService,
createReactRouterNavigationAdapter,
} from 'ptech-shell-react';The root entry stays react-router runtime-free. It exports:
createMsalUserServicecreateReactRouterNavigationAdapter- related MSAL and navigation adapter types
React Router subpath:
import {
ShellRouterBridge,
ShellRouterProvider,
detectBasenameFromKnownRoots,
} from 'ptech-shell-react/react-router';Import this subpath only in code that has React Router available.
MSAL bootstrap subpath:
import {
buildMsalConfiguration,
createMsalInstance,
createMsalRedirectHooks,
planInteractiveAuthRedirect,
} from 'ptech-shell-react/msal';Import ./msal when bootstrapping MSAL at app startup (no React required).
MSAL React subpath:
import {
MsalAuthGate,
useAuth,
} from 'ptech-shell-react/msal-react';Import ./msal-react only under <MsalProvider>.
MSAL User Service
Use createMsalUserService in production hosts that authenticate through MSAL.
import { registerService, TOKENS } from 'ptech-shell-sdk';
import { createMsalUserService } from 'ptech-shell-react';
registerService(
TOKENS.userService,
createMsalUserService({
msal,
defaultScopes: ['api://example/access_as_user'],
loginMode: 'redirect',
logoutMode: 'redirect',
tokenInteractionMode: 'redirect',
storageKeyPrefix: 'my-portal',
additionalInteractionRequiredErrorCodes: ['ciam_policy_error'],
}),
);Redirect-mode user services now install the two-attempt loop breaker by default
when beforeInteractiveRedirect is omitted. Pass a custom hook only when the
host deliberately owns equivalent policy. storageKeyPrefix isolates the
bookkeeping for products sharing an origin.
Silent token acquisition falls back to interaction only for an
InteractionRequiredAuthError name or one of the MSAL Common v16
interaction-required error codes. Network, configuration, and other silent
failures are rethrown unchanged. Concurrent popup requests with the same
account, scopes, and claims share one promise; different popup requests are
serialized so MSAL never receives overlapping popup interactions. The root
entry preserves @azure/msal-browser as an optional peer and therefore uses
cross-bundle-safe error duck typing rather than instanceof.
MSAL Bootstrap and Auth Gate
Use createMsalInstance once at startup, wrap the app with MsalProvider, then gate rendering with MsalAuthGate:
import { MsalProvider } from '@azure/msal-react';
import {
buildMsalConfiguration,
createMsalInstance,
} from 'ptech-shell-react/msal';
import { MsalAuthGate } from 'ptech-shell-react/msal-react';
const storageKeyPrefix = 'my-portal';
const msalConfig = buildMsalConfiguration({
clientId: import.meta.env.PUBLIC_MSAL_CLIENT_ID,
authority: import.meta.env.PUBLIC_MSAL_AUTHORITY,
knownAuthorities: [import.meta.env.PUBLIC_MSAL_KNOWN_AUTHORITY],
});
const msal = await createMsalInstance(msalConfig, { storageKeyPrefix });
<MsalProvider instance={msal}>
<MsalAuthGate
requireAccessToken
tokenScopes={['api://example/access_as_user']}
storageKeyPrefix={storageKeyPrefix}
renderRecoveryScreen={(retry) => (
<AuthRedirectRecovery onRetry={retry} />
)}
>
<App />
</MsalAuthGate>
</MsalProvider>MsalAuthGate limits automatic login/token redirects to two attempts per
return path by default. The second attempt clears the affected account and uses
prompt: 'login'; a third automatic attempt stops. Supply
renderRecoveryScreen for consumer-localized recovery UI. Its callback clears
the attempt state and performs an explicit fresh-login retry. If no recovery
renderer is supplied, the gate throws MsalRedirectLimitError so the owning
error boundary can render a nonblank recovery surface (branch on error.name;
the class is intentionally internal). Set disableRedirectAttemptCap only when
the host deliberately provides equivalent loop protection; a positive finite
integer redirectAttemptCap selects a different cap. Invalid numeric caps throw
RangeError before an interactive redirect starts.
For direct MSAL hook usage (outside the shell UserService contract), use
useAuth from ptech-shell-react/msal-react. It acquires and refreshes tokens
for the active account, hides a cached token immediately when the account
changes, and suspends auto-acquisition after sign-out starts so a token cannot
be reacquired while MSAL is navigating away. isLoading remains true during
that sign-out handoff and resets when the MSAL context reports no active
account (or logout rejects).
The adapter implements the SDK UserService contract:
getSnapshotgetSessionacquireAccessTokenloginlogoutsubscribe
Host-specific claim mapping belongs in mapUser; keep product-specific mapping out of this package.
React Router Navigation
Use createReactRouterNavigationAdapter when wiring React Router to the SDK NavigationService contract directly.
import { registerService, TOKENS } from 'ptech-shell-sdk';
import { createReactRouterNavigationAdapter } from 'ptech-shell-react';
const adapter = createReactRouterNavigationAdapter({ basename: '/audit-tool' });
registerService(TOKENS.navigation, adapter.service);App-Owned Router
Use ShellRouterProvider when the app owns its top-level router.
import { ShellRouterProvider } from 'ptech-shell-react/react-router';
export function AppRoot() {
return (
<ShellRouterProvider basename="/audit-tool">
<AppRoutes />
</ShellRouterProvider>
);
}ShellRouterProvider creates/registers the navigation adapter and renders a BrowserRouter.
Host-Owned Router
Use ShellRouterBridge when a remote is mounted inside a router owned by the host. Do not nest another router in this topology.
import { registerService, TOKENS } from 'ptech-shell-sdk';
import { createReactRouterNavigationAdapter } from 'ptech-shell-react';
import { ShellRouterBridge } from 'ptech-shell-react/react-router';
const adapter = createReactRouterNavigationAdapter({ basename: '/t/demo/audit-tool' });
registerService(TOKENS.navigation, adapter.service);
export function RemoteRoot() {
return (
<>
<ShellRouterBridge adapter={adapter} basename="/t/demo/audit-tool" />
<RemoteRoutes />
</>
);
}Basename Detection
Prefer an explicit basename. detectBasenameFromKnownRoots is a fallback for older remotes that need to infer a host mount prefix from the current path.
import { detectBasenameFromKnownRoots } from 'ptech-shell-react/react-router';
const basename = detectBasenameFromKnownRoots(window.location.pathname, [
'audit-tool',
'settings',
]);Build
npm run build -w ptech-shell-react
npm run test -w ptech-shell-reactThe build has four entries:
.: MSAL user service and navigation adapter, without importing React Router or MSAL React../react-router: React Router components and helpers../msal: MSAL bootstrap utilities (createMsalInstance, redirect loop breaker)../msal-react:MsalAuthGateanduseAuth(requires@azure/msal-react).
The React test harness uses React 19 act, jsdom, a fake MSAL context, and
react-dom to cover the auth-gate state machine and token lifecycle without a
real tenant or browser redirect. These are development-only dependencies and do
not change the package's runtime peer surface.
