@cloudscaile-eng/web-ext-utils
v0.0.8
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,
triggerGuestLogin: triggerGuestLoginFunction,
triggerLogout: triggerLogoutFunction,
getCookieConsent: getCookieConsentFunction,
updateCookieConsent: updateCookieConsentFunction,
resetCookieConsent: resetCookieConsentFunction,
trackGA4Event: trackGA4EventFunction,
trackGTMEvent: trackGTMEventFunction,
getOAuthProviders: getOAuthProvidersFunction,
triggerSendOTP: triggerSendOtpFunction,
triggerSignUp: triggerSignUpFunction
});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,
triggerGuestLogin,
triggerLogout,
getCookieConsent,
updateCookieConsent,
resetCookieConsent,
trackGA4Event,
trackGTMEvent,
getOAuthProviders,
triggerSendOTP,
triggerSignUp,
OTP_INTENT
} 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 guest login (host generates/persists the browser id automatically)
const guestResult = await triggerGuestLogin(extension, { redirect: '/home/dash' });
if (guestResult?.success) {
console.log('Logged in as guest', guestResult.data);
}
// Trigger logout with redirect
await triggerLogout(extension, { redirect: '/home/login' });
// Cookie consent (defaults to targeting all providers: ['ga4', 'gtm'])
const consent = getCookieConsent(extension); // { status: 'pending', timestamp: null }
updateCookieConsent(extension, 'accepted');
resetCookieConsent(extension);
// Cookie consent targeting a specific analytics provider
updateCookieConsent(extension, 'accepted', ['gtm']);
resetCookieConsent(extension, ['ga4']);
// Track GA4 events (no-ops if consent not given)
trackGA4Event(extension, 'login', { method: 'email' });
trackGA4Event(extension, 'purchase', { item: 'cart', value: 49 });
// Track GTM events (no-ops if consent not given)
trackGTMEvent(extension, 'login', { method: 'email' });
trackGTMEvent(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 }, ...]
// Send an OTP (tenant is injected by the host; extensions never pass or see it)
const otpResult = await triggerSendOTP(extension, { email: '[email protected]', intent: OTP_INTENT.REGISTER });
// Sign up a new user with a verified OTP. On success, the host logs the user in immediately.
const signUpResult = await triggerSignUp(extension, {
email: '[email protected]',
password: 'secret',
firstName: 'Jane',
lastName: 'Doe',
otp: '123456'
});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.triggerGuestLogin: Function to trigger guest 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. Accepts an optionalprovidersarray (('ga4' | 'gtm')[]) to target specific analytics providers; defaults to both.config.resetCookieConsent: Function to reset consent state and stop analytics events. Accepts an optionalprovidersarray (('ga4' | 'gtm')[]) to target specific analytics providers; defaults to both.config.trackGA4Event: Function to track a GA4 event.config.trackGTMEvent: Function to track a GTM event.config.getOAuthProviders: Function to get the list of available OAuth providers.config.triggerSendOTP: Function to send an OTP to an email for a given intent.config.triggerSignUp: Function to register a new user; logs them in on success.
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().
Returns:
| Field | Type | Description |
|---|---|---|
| data | object \| null | The authenticated user's data, or null if not authenticated |
| authenticated | boolean | Whether the current user is authenticated |
| browserId | string | Host-generated/persisted id identifying this browser, used for guest sessions |
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.
triggerGuestLogin(extension, config)
Triggers the host to log the current user in as a guest for the current tenant. The host generates/persists the browser id and injects the tenant identifier automatically.
Parameters
extension: Extension object fromgetExtension().config.redirect: Path to navigate to after a successful login.
Returns:
Promise<{ success: true; data: unknown } | { success: false; error: unknown } | 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, providers?)
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'.providers: Optional array of analytics providers to target (('ga4' | 'gtm')[]). Defaults to both.
resetCookieConsent(extension, providers?)
Resets the cookie consent state and stops further analytics events by calling resetAnalytics().
Parameters:
extension: Extension object fromgetExtension().providers: Optional array of analytics providers to target (('ga4' | 'gtm')[]). Defaults to both.
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' }).
trackGTMEvent(extension, eventName, params?)
Tracks a GTM event by pushing to the dataLayer. Silently no-ops if GTM has not been initialized (i.e. consent not yet given).
Parameters:
extension: Extension object fromgetExtension().eventName: The event name pushed to the GTM dataLayer (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 |
triggerSendOTP(extension, params)
Sends an OTP to the given email for the given intent. The host injects the tenant identifier automatically; extensions never pass or receive it.
Parameters:
extension: Extension object fromgetExtension().params.email: The email address to send the OTP to.params.intent: One of theOTP_INTENTvalues —'RESET_PASSWORD','REGISTER', or'EMAIL_VERIFICATION'.
Returns:
Promise<{ success: boolean; data?: unknown; error?: unknown }>
triggerSignUp(extension, params)
Registers a new user with the host application. The host injects the tenant identifier automatically. On success, the host logs the user in immediately, the same effect as a successful triggerLogin.
Parameters:
extension: Extension object fromgetExtension().params.email: The new user's email.params.password: The new user's password.params.firstName: The new user's first name.params.lastName: The new user's last name.params.otp: The OTP previously verified viatriggerSendOTP.
Returns:
Promise<{ success: boolean; data?: unknown; error?: unknown }>
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
