@cloudscaile-eng/web-ext-utils
v0.0.5
Published
Utilities for sharing host resources with micro-frontends in web applications
Readme
Web Extension Utils
Extension utilities for micro-frontend architecture.
Installation
Install the package:
npm install @cloudscaile-eng/web-ext-utilsPeer Dependencies
This package requires the following peer dependencies to be installed in the host application:
npm install @mui/material @reduxjs/toolkit axiosNote on TypeScript Support: TypeScript type definitions for peer dependencies are bundled with this package's distribution. You will receive full IntelliSense support even during the initial installation. However, at runtime, the peer dependencies must be installed in your project for the package to function correctly.
Host Application
The host application must initialize shared resources before any micro-frontends can access them.
import { initializeHost } from '@cloudscaile-eng/web-ext-utils';
const hostAPI = initializeHost({
extAxios: axiosFunction,
reduxStore: store,
eventBus: eventBusInstance,
injectReducers: injectReducerFunction,
registerTranslation: registerTranslationFunction,
theme: themeObject,
toast: toastFunction,
getUser: getUserFunction,
validateUserPermission: validateUserPermissionFunction,
triggerLogin: triggerLoginFunction,
triggerLogout: triggerLogoutFunction,
getCookieConsent: getCookieConsentFunction,
updateCookieConsent: updateCookieConsentFunction,
resetCookieConsent: resetCookieConsentFunction,
trackGA4Event: trackGA4EventFunction,
getOAuthProviders: getOAuthProvidersFunction
});Micro-Frontend Application
A micro-frontend can access shared resources using individual functions with an extension object.
import {
getExtension,
getExtAxios,
getReduxStore,
getEventBus,
injectReducers,
registerTranslation,
getNsForTranslation,
getTheme,
toast,
getUser,
validateUserPermission,
triggerLogin,
triggerLogout,
getCookieConsent,
updateCookieConsent,
resetCookieConsent,
trackGA4Event,
getOAuthProviders
} from '@cloudscaile-eng/web-ext-utils';
// Create extension object
const extension = getExtension('<tenant>', '<extension>');
// Access shared resources
const axiosInstance = getExtAxios(extension, { errorToast: true });
const store = getReduxStore(extension);
const eventBus = getEventBus(extension);
// Inject additional reducers into the host application
injectReducers(extension, {
reducers: { auth: authSlice.reducer },
whitelist: ['auth']
});
// Register translations
registerTranslation(extension, {
ns: 'auth',
translation: { en: { login: 'Login', logout: 'Logout' } }
});
// Get namespace for translations
const ns = getNsForTranslation(extension, 'auth');
// Access theme, show toast, and get user information
const theme = getTheme(extension);
toast(extension, 'Welcome!', 'success');
const user = getUser(extension);
const permissions = validateUserPermission(extension, ['payment.refund', 'inventory.bill']); // Returns {"payment.refund": true, "inventory.bill": false}
// Trigger login – redirect only (navigates to auth page, returns after login)
triggerLogin(extension, { redirect: '/home/dash' });
// Trigger login – SSO / social provider
triggerLogin(extension, { provider: 'google', redirect: '/home/dash' });
// Trigger login – email / password (returns { success, data } or { success, error })
const result = await triggerLogin(extension, { email: '[email protected]', password: 'secret', redirect: '/home/dash' });
if (result?.success) {
console.log('Logged in', result.data);
}
// Trigger logout with redirect
await triggerLogout(extension, { redirect: '/home/login' });
// Cookie consent
const consent = getCookieConsent(extension); // { status: 'pending', timestamp: null }
updateCookieConsent(extension, 'accepted');
resetCookieConsent(extension);
// Track GA4 events (no-ops if consent not given)
trackGA4Event(extension, 'login', { method: 'email' });
trackGA4Event(extension, 'purchase', { item: 'cart', value: 49 });
// Get configured OAuth / SSO providers (sorted by order in the host)
const providers = getOAuthProviders(extension);
// providers → [{ value: 'google', name: 'Google', displayName: 'Continue with Google', icon: '/icons/google.svg', order: 1 }, ...]API Reference
initializeHost(config)
Initializes shared resources in the host application.
Parameters
config.extAxios: The shared Axios instance function.config.reduxStore: The shared Redux store.config.eventBus: The shared event bus.config.injectReducers: Function to inject reducers into the host.config.registerTranslation: Function to register translations into the host.config.theme: Theme object to share with micro-frontends.config.toast: Function to show toast notifications.config.getUser: Function to get user information.config.validateUserPermission: Function to validate user permissions.config.triggerLogin: Function to trigger login in the host.config.triggerLogout: Function to trigger logout in the host.config.getCookieConsent: Function to retrieve the current cookie consent state.config.updateCookieConsent: Function to dispatch consent actions and initialize analytics on acceptance.config.resetCookieConsent: Function to reset consent state and stop analytics events.config.trackGA4Event: Function to track a GA4 event.config.getOAuthProviders: Function to get the list of available OAuth providers.
Returns
getSharedResources(): Returns the shared resources object.
getExtension(tenant, name)
Creates an extension object with tenant and name identifiers.
Parameters
tenant: The tenant identifier specified in the manifest.name: The extension name as defined in the manifest.
Returns
Extension object.
Individual Resource Functions
All resource functions require an extension object as the first parameter:
getExtAxios(extension, config)
Returns the shared Axios instance with optional configuration.
Parameters:
extension: Extension object fromgetExtension().config: Optional configuration object with properties likeerrorToast,errorMessage,host,type,open,local.
getReduxStore(extension)
Returns the shared Redux store.
Parameters:
extension: Extension object fromgetExtension().
getEventBus(extension)
Returns the shared event bus.
Parameters:
extension: Extension object fromgetExtension().
injectReducers(extension, options)
Injects reducers into the host application.
Parameters:
extension: Extension object fromgetExtension().options: Object withreducers,whitelist, andreplaceproperties.
registerTranslation(extension, options)
Registers translations into the host application.
Parameters:
extension: Extension object fromgetExtension().options: Object withns(namespace) andtranslationproperties.
getNsForTranslation(extension, extensionNs)
Returns the namespace string for translations.
Parameters:
extension: Extension object fromgetExtension().extensionNs: The extension-specific namespace.
getTheme(extension)
Returns the shared theme object.
Parameters:
extension: Extension object fromgetExtension().
toast(extension, message, type)
Shows a toast notification.
Parameters:
extension: Extension object fromgetExtension().message: The message to display.type: Toast type ('success', 'error', 'info', 'warn').
getUser(extension)
Returns the user information from the host application.
Parameters:
extension: Extension object fromgetExtension().
validateUserPermission(extension, permissions)
Validates user permissions for the given extension.
Parameters:
extension: Extension object fromgetExtension().permissions: Array of permission keys (e.g.,['payment.refund', 'inventory.bill']).
Returns:
An object mapping each permission to a boolean (e.g., {"payment.refund": true, "inventory.bill": false}).
triggerLogin(extension, config)
Triggers the login process in the host application. Supports three modes:
| Mode | Config supplied | Behaviour |
|---|---|---|
| Redirect only | redirect | Navigates to the auth page; returns to redirect after login |
| SSO / social | provider (+ optional redirect) | Redirects the browser to the configured SSO URL |
| Credential login | email + password (+ optional redirect) | Calls the login API, stores tokens and user in Redux |
Parameters
extension: Extension object fromgetExtension().config.redirect: Path to navigate to after a successful login (all modes).config.email: User email for direct credential login.config.password: User password for direct credential login.config.provider: Social / SSO provider identifier (e.g.'google').
Returns:
Promise<{ success: true; data: unknown } | { success: false; error: unknown } | undefined>
Returns a result object only for credential login. SSO and redirect flows return undefined.
triggerLogout(extension, config)
Triggers the logout process in the host application for the given extension.
Parameters
extension: Extension object fromgetExtension().config.redirect: Path to navigate to after logout completes.
Returns:
Promise<void>
getCookieConsent(extension)
Returns the current cookie consent state from the host Redux store.
Parameters:
extension: Extension object fromgetExtension().
Returns:
An object with status ('accepted' | 'declined' | 'pending') and timestamp (string | null).
updateCookieConsent(extension, status)
Updates cookie consent by dispatching acceptConsent or declineConsent. When status is 'accepted', also calls initializeAnalytics with the tenant's measurementId.
Parameters:
extension: Extension object fromgetExtension().status: The consent status to set —'accepted'or'declined'.
resetCookieConsent(extension)
Resets the cookie consent state and stops further analytics events by calling resetAnalytics().
Parameters:
extension: Extension object fromgetExtension().
trackGA4Event(extension, eventName, params?)
Tracks a GA4 event. Silently no-ops if analytics has not been initialized (i.e. consent not yet given).
Parameters:
extension: Extension object fromgetExtension().eventName: The GA4 event name (e.g.'login','purchase').params: Optional object of event parameters (e.g.{ method: 'email' }).
getOAuthProviders(extension)
Returns the list of OAuth / SSO login providers configured by the host application.
Parameters:
extension: Extension object fromgetExtension().
Returns:
An array of OAuthProvider objects:
| Field | Type | Description |
|---|---|---|
| value | string | Unique provider identifier (e.g. 'google') |
| name | string | Provider name used as icon alt text |
| displayName | string | Label shown on the login button |
| icon | string | URL or path to the provider's icon image |
| order | number | Sort order relative to other providers |
Error Handling
- If the host has not initialized resources, individual resource functions will throw an error.
- Ensure
initializeHost()is called before loading any micro-frontends. - If required resources are missing during host initialization, an error will be thrown.
- Extension validation will throw errors if
tenantornameis missing from the extension
