@opensourcekd/ng-common-libs
v1.2.5
Published
Angular 18 shareable utility library with framework-agnostic core and Angular wrappers for event emitter, authorization, storage, and more
Maintainers
Readme
ng-common-libs
Angular 18 library with Auth0 authentication service and MicroFrontend event bus.
🎯 Dual-Layer Architecture
This library features a dual-layer architecture:
- Core Layer (
@opensourcekd/ng-common-libs/core): Framework-agnostic event bus using only RxJS. Use in React, Vue, Svelte, or vanilla JavaScript projects. - Angular Layer (
@opensourcekd/ng-common-libsor/angular): Angular-specific services with dependency injection.
🚀 Features
- EventBusService: MicroFrontend-ready event bus with replay buffer for cross-app communication
- Auth0 Integration: Complete Auth0 authentication service with token management
📦 Installation
npm install @opensourcekd/ng-common-libsNote:
mittand@auth0/auth0-spa-jsare bundled with the library. You don't need to install them separately.Module Federation: Just configure
@opensourcekd/ng-common-libsas shared in your webpack config. The bundled dependencies (mitt,@auth0/auth0-spa-js) will be included automatically, ensuring they're loaded only once across all micro-frontends.
🔧 Usage
Auth0 Authentication
Complete Auth0 integration with automatic token management and event emission:
import { Component, inject } from '@angular/core';
import { AuthService, configureAuth0 } from '@opensourcekd/ng-common-libs';
// Configure Auth0 in your app.config.ts
configureAuth0({
domain: 'your-domain.auth0.com',
clientId: 'your-client-id',
audience: 'https://your-api.com',
});
@Component({
selector: 'app-login',
template: `
<button (click)="login()">Login with Auth0</button>
<button (click)="logout()" *ngIf="user">Logout</button>
<div *ngIf="user">Welcome, {{ user.name }}!</div>
`
})
export class LoginComponent {
private authService = inject(AuthService);
user = this.authService.getUser();
async login() {
await this.authService.login();
}
async logout() {
await this.authService.logout();
}
}See the Auth0 Service Usage Guide for complete integration instructions.
EventBusService
Cross-application event communication for MicroFrontend architectures:
import { Component, OnInit, inject } from '@angular/core';
import { EventBusService } from '@opensourcekd/ng-common-libs';
@Component({
selector: 'app-event-example',
template: `<button (click)="sendEvent()">Send Event</button>`
})
export class EventExampleComponent implements OnInit {
private eventBus = inject(EventBusService);
ngOnInit() {
// Subscribe to all events
this.eventBus.onePlusNEvents.subscribe(event => {
console.log('Event received:', event);
});
}
sendEvent() {
// Send structured event
this.eventBus.sendEvent(JSON.stringify({
type: 'user:action',
payload: { userId: '123' },
timestamp: new Date().toISOString()
}));
}
}See the EventBus Service Usage Guide for advanced patterns and MicroFrontend examples.
For Non-Angular Projects (React, Vue, Svelte, Vanilla JS)
Use the framework-agnostic core event bus:
// Import from /core
import { EventBus } from '@opensourcekd/ng-common-libs/core';
// Event Bus
const eventBus = new EventBus();
eventBus.emit('user:login', { userId: '123' });
eventBus.on('user:login').subscribe(data => {
console.log('User logged in:', data);
});React Example
import { useEffect } from 'react';
import { EventBus } from '@opensourcekd/ng-common-libs/core';
const eventBus = new EventBus();
function MyComponent() {
useEffect(() => {
const subscription = eventBus.on('user:login').subscribe(data => {
console.log('User logged in:', data);
});
return () => subscription.unsubscribe();
}, []);
const handleLogin = () => {
eventBus.emit('user:login', { userId: '123' });
};
return <button onClick={handleLogin}>Login</button>;
}Vue Example
import { onMounted, onUnmounted } from 'vue';
import { EventBus } from '@opensourcekd/ng-common-libs/core';
const eventBus = new EventBus();
export default {
setup() {
let subscription;
onMounted(() => {
subscription = eventBus.on('user:login').subscribe(data => {
console.log('User logged in:', data);
});
});
onUnmounted(() => {
subscription?.unsubscribe();
});
const handleLogin = () => {
eventBus.emit('user:login', { userId: '123' });
};
return { handleLogin };
}
};📚 Documentation
- Auth0 Service Usage - Complete Auth0 authentication integration guide
- EventBus Service Usage - Cross-application event communication guide
- Deployment Guide - Publishing, versioning, and consumption
- Microapp Triggering Guide - Automatic build triggering for consuming microapps
- Module Federation Guide - Runtime sharing with Module Federation
📝 API Documentation
AuthService
login(options?: RedirectLoginOptions): Promise<void>- Initiate Auth0 loginlogout(options?: LogoutOptions): Promise<void>- Logout and clear sessionhandleCallback(): Promise<{ success: boolean, appState?: any }>- Handle Auth0 callbackgetToken(): Promise<string | null>- Get access token asynchronouslygetTokenSync(): string | null- Get cached access token synchronouslygetUser(): Signal<UserInfo | null>- Get user information as signalisAuthenticated(): Signal<boolean>- Check authentication statusisLoading(): Signal<boolean>- Check if authentication is loading
EventBusService
sendEvent(event: string): void- Send event to all subscribersonePlusNEvents: Observable<string>- Subscribe to all events with replay buffer
EventBus (Core)
emit<T>(eventType: string, data?: T): void- Emit an eventon<T>(eventType: string): Observable<T>- Subscribe to an eventonMultiple(eventTypes: string[]): Observable<EventPayload>- Subscribe to multiple eventsonAll(): Observable<EventPayload>- Subscribe to all events
🛠️ Development
# Install dependencies
npm install
# Build the library
npm run build
# Run linter
npm run lint📄 License
MIT
👤 Author
Koustubh Desai [email protected]
🤝 Contributing
Contributions, issues, and feature requests are welcome!
⭐ Show your support
Give a ⭐️ if this project helped you!
