npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

ptech-shell-react

v2.16.0

Published

Production React adapters (MSAL bootstrap, auth gate, user service, react-router navigation) for Module Federation shell apps.

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:

  • createMsalUserService
  • createReactRouterNavigationAdapter
  • 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.

Silent renewal and the MSAL redirect bridge

By default MSAL Browser v5 returns the result of a silent (hidden iframe) or popup request only through its redirect bridge: the page loaded at redirectUri has to broadcast the response to the window that started the request. The hidden iframe is what renews a session once the refresh token can no longer be used, which for a single-page app happens 24 hours after sign-in.

buildMsalConfiguration uses the application page as redirectUri unless the host sets another one, so createMsalInstance acts as that bridge. When the page was loaded as the redirect target of a silent or popup request, it hands the response to the waiting window. In the hidden iframe it then never resolves: that frame must not start a second application, and MSAL removes it. Every other load, including the response of a full-page redirect, starts MSAL as before. No extra page and no extra redirect URI registration are needed. A host that points redirectUri at a different page has to run the bridge on that page instead.

Without the bridge the request waits out MSAL's bridge timeout, by default ten seconds for the hidden iframe and sixty for a popup, and ends in timed_out (redirect_bridge_timeout). The session then cannot be renewed until the user signs in again, and API calls go out without a usable token.

The bridge only delivers the response. Whether the identity provider can answer a hidden-iframe request is up to the browser: where it blocks the identity provider's cookies inside a frame (third-party cookies), the answer is an interaction-required error. With the bridge that error reaches the application instead of a timeout, and the host signs the user in interactively.

The same timeout limits the bridge: the hidden iframe has to load the page and reach the bridge before it runs out. createMsalInstance reaches the bridge only after the host has loaded far enough to call it, so a host whose startup is not short should run the same check first thing in its entry module, before anything reads or rewrites the URL:

import { handleMsalRedirectBridge } from 'ptech-shell-react/msal';

if (!(await handleMsalRedirectBridge())) {
  await import('./bootstrap');
}

This import brings @azure/msal-browser into the entry module. A host that wants to keep it out can first test the query string and the fragment of the URL for a code, error or state parameter and import ptech-shell-react/msal only when one is present.

handleMsalRedirectBridge resolves to true when the page was loaded in the hidden iframe to deliver a response, and the host must then stop. A popup response is delivered the same way, and the popup then closes itself; a window that is still open shortly afterwards is treated as an ordinary window, so the call resolves to false and the application starts as usual. After a delivery, every later call on the same page returns the first answer, so calling it in the entry module and again through createMsalInstance is safe. It does not look at the MSAL configuration, so a host that set system.enableLegacyPolling must not call it; createMsalInstance skips the bridge for such a host.

Because the application page is the bridge page, it has to meet two conditions:

  • MSAL's rule for a redirect bridge page applies to it: it must not be served with a Cross-Origin-Opener-Policy header. See Set up the redirect bridge page.
  • It must be allowed to load in a frame on its own origin (frame-ancestors 'self', and no X-Frame-Options: DENY), and the page that starts the request must allow both its own origin and the identity provider as frame sources (frame-src including 'self' and the authority). The hidden iframe goes to the identity provider first and comes back to the application page.

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:

  • getSnapshot
  • getSession
  • acquireAccessToken
  • login
  • logout
  • subscribe

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-react

The 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: MsalAuthGate and useAuth (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.