Core utilities including event hub, caching, logging, storage abstractions, internationalization, and service worker support. These utilities provide foundational functionality for Amplify applications.
import {
Hub, I18n, Cache, ConsoleLogger,
ServiceWorker, parseAmplifyConfig
} from "aws-amplify/utils";Centralized event system for cross-module communication and application-wide messaging.
/**
* Hub for application-wide event communication
*/
interface Hub {
/**
* Dispatch an event to all listeners
* @param channel - Event channel name
* @param payload - Event data
* @param source - Event source identifier (optional)
*/
dispatch(channel: string, payload: HubPayload, source?: string): void;
/**
* Listen for events on a specific channel
* @param channel - Channel to listen on
* @param callback - Function to call when event is received
* @returns HubCapsule for managing the listener
*/
listen(channel: string, callback: HubCallback): HubCapsule;
/**
* Remove a specific listener
* @param channel - Channel to remove listener from
* @param listener - HubCapsule returned from listen()
*/
remove(channel: string, listener: HubCapsule): void;
}
interface HubPayload {
event: string;
data?: any;
message?: string;
}
type HubCallback = (data: HubCapsule) => void;
interface HubCapsule {
channel: string;
payload: HubPayload;
source: string;
patternInfo?: string;
}Hub Usage Examples:
import { Hub } from "aws-amplify/utils";
// Listen for authentication events
const authListener = Hub.listen('auth', (data) => {
const { channel, payload } = data;
switch (payload.event) {
case 'signedIn':
console.log('User signed in:', payload.data);
break;
case 'signedOut':
console.log('User signed out');
break;
case 'tokenRefresh':
console.log('Token refreshed');
break;
}
});
// Listen for DataStore events
const dataStoreListener = Hub.listen('datastore', (data) => {
const { payload } = data;
if (payload.event === 'ready') {
console.log('DataStore is ready');
} else if (payload.event === 'networkStatus') {
console.log('Network status:', payload.data.active);
}
});
// Dispatch custom events
Hub.dispatch('myApp', {
event: 'userAction',
data: {
action: 'buttonClick',
buttonId: 'submit'
}
}, 'MyComponent');
// Listen for custom events
const customListener = Hub.listen('myApp', (data) => {
console.log('Custom event:', data.payload);
});
// Clean up listeners
Hub.remove('auth', authListener);
Hub.remove('datastore', dataStoreListener);
Hub.remove('myApp', customListener);Multi-language support and localization utilities.
/**
* Internationalization utility for multi-language support
*/
interface I18n {
/**
* Get localized string for a key
* @param key - Translation key
* @param options - Interpolation options
* @returns Localized string
*/
get(key: string, options?: object): string;
/**
* Add vocabulary/translations for languages
* @param vocabularies - Object containing translations by language
* @returns I18n instance for chaining
*/
putVocabularies(vocabularies: Vocabularies): I18n;
/**
* Set the current language
* @param language - Language code (e.g., 'en', 'es', 'fr')
* @returns I18n instance for chaining
*/
setLanguage(language: string): I18n;
/**
* Get the current language
* @returns Current language code
*/
getLanguage(): string;
}
interface Vocabularies {
[language: string]: {
[key: string]: string;
};
}I18n Usage Examples:
import { I18n } from "aws-amplify/utils";
// Define vocabularies
const vocabularies = {
en: {
'welcome': 'Welcome',
'greeting': 'Hello {{name}}',
'signIn': 'Sign In',
'signOut': 'Sign Out',
'error.invalidCredentials': 'Invalid username or password'
},
es: {
'welcome': 'Bienvenido',
'greeting': 'Hola {{name}}',
'signIn': 'Iniciar Sesión',
'signOut': 'Cerrar Sesión',
'error.invalidCredentials': 'Usuario o contraseña inválidos'
},
fr: {
'welcome': 'Bienvenue',
'greeting': 'Bonjour {{name}}',
'signIn': 'Se Connecter',
'signOut': 'Se Déconnecter',
'error.invalidCredentials': 'Nom d\'utilisateur ou mot de passe invalide'
}
};
// Set up vocabularies
I18n.putVocabularies(vocabularies);
// Set language
I18n.setLanguage('en');
// Get translations
console.log(I18n.get('welcome')); // "Welcome"
console.log(I18n.get('greeting', { name: 'John' })); // "Hello John"
// Change language
I18n.setLanguage('es');
console.log(I18n.get('welcome')); // "Bienvenido"
console.log(I18n.get('greeting', { name: 'Juan' })); // "Hola Juan"
// Get current language
const currentLang = I18n.getLanguage(); // "es"Client-side caching utilities for improved performance.
/**
* Cache utility for storing and retrieving data
*/
interface Cache {
/**
* Store an item in cache
* @param key - Cache key
* @param value - Value to cache
* @param options - Cache options
* @returns Promise that resolves when item is cached
*/
setItem(key: string, value: any, options?: CacheOptions): Promise<void>;
/**
* Retrieve an item from cache
* @param key - Cache key
* @returns Promise with cached value or null if not found
*/
getItem(key: string): Promise<any>;
/**
* Remove an item from cache
* @param key - Cache key
* @returns Promise that resolves when item is removed
*/
removeItem(key: string): Promise<void>;
/**
* Clear all cached items
* @returns Promise that resolves when cache is cleared
*/
clear(): Promise<void>;
/**
* Get all cache keys
* @returns Promise with array of cache keys
*/
getAllKeys(): Promise<string[]>;
/**
* Get cache size information
* @returns Promise with cache size details
*/
getCacheSize(): Promise<number>;
}
interface CacheOptions {
expires?: number; // TTL in milliseconds
priority?: 1 | 2 | 3 | 4 | 5; // Cache priority (1 = highest)
}Cache Usage Examples:
import { Cache } from "aws-amplify/utils";
// Cache data with expiration
await Cache.setItem('user_profile', {
id: 'user123',
name: 'John Doe',
email: 'john@example.com'
}, {
expires: 3600000, // 1 hour
priority: 1
});
// Retrieve cached data
const userProfile = await Cache.getItem('user_profile');
if (userProfile) {
console.log('Cached user:', userProfile);
} else {
console.log('User not in cache, fetch from API');
}
// Cache API responses
const cacheApiResponse = async (endpoint: string) => {
const cached = await Cache.getItem(`api_${endpoint}`);
if (cached) {
return cached;
}
const response = await fetch(endpoint);
const data = await response.json();
await Cache.setItem(`api_${endpoint}`, data, {
expires: 300000 // 5 minutes
});
return data;
};
// Clear specific items
await Cache.removeItem('user_profile');
// Clear all cache
await Cache.clear();
// Get cache statistics
const keys = await Cache.getAllKeys();
const size = await Cache.getCacheSize();
console.log(`Cache has ${keys.length} items, ${size} bytes`);Configurable logging system for debugging and monitoring.
/**
* Console logger with configurable levels
*/
interface ConsoleLogger {
/**
* Log debug message (lowest level)
* @param message - Log message
* @param optionalParams - Additional parameters
*/
debug(message: any, ...optionalParams: any[]): void;
/**
* Log info message
* @param message - Log message
* @param optionalParams - Additional parameters
*/
info(message: any, ...optionalParams: any[]): void;
/**
* Log warning message
* @param message - Log message
* @param optionalParams - Additional parameters
*/
warn(message: any, ...optionalParams: any[]): void;
/**
* Log error message (highest level)
* @param message - Log message
* @param optionalParams - Additional parameters
*/
error(message: any, ...optionalParams: any[]): void;
}
type LogLevel = 'DEBUG' | 'INFO' | 'WARN' | 'ERROR' | 'NONE';Logger Usage Examples:
import { ConsoleLogger } from "aws-amplify/utils";
// Create logger instance
const logger = new ConsoleLogger('MyApp');
// Log at different levels
logger.debug('Debug information', { userId: 'user123' });
logger.info('User signed in successfully');
logger.warn('API rate limit approaching');
logger.error('Failed to save data', new Error('Network timeout'));
// Configure log level (only logs at this level and above will be shown)
logger.setLevel('WARN'); // Only shows WARN and ERROR
// Create category-specific loggers
const authLogger = new ConsoleLogger('Auth');
const apiLogger = new ConsoleLogger('API');
authLogger.info('Authentication attempt');
apiLogger.error('API request failed');Service worker utilities for PWA functionality and offline capabilities.
/**
* Service Worker registration and management
*/
interface ServiceWorker {
/**
* Register a service worker
* @param swUrl - Service worker script URL
* @param options - Registration options
* @returns Promise with registration result
*/
register(swUrl: string, options?: ServiceWorkerOptions): Promise<boolean>;
/**
* Unregister the service worker
* @returns Promise that resolves when unregistered
*/
unregister(): Promise<void>;
/**
* Send message to service worker
* @param message - Message to send
* @returns Promise with response from service worker
*/
send(message: any): Promise<any>;
/**
* Check if service worker is supported
* @returns Boolean indicating support
*/
isSupported(): boolean;
}
interface ServiceWorkerOptions {
scope?: string;
updateViaCache?: 'imports' | 'all' | 'none';
}Service Worker Examples:
import { ServiceWorker } from "aws-amplify/utils";
// Check if service worker is supported
if (ServiceWorker.isSupported()) {
// Register service worker
const registered = await ServiceWorker.register('/sw.js', {
scope: '/',
updateViaCache: 'none'
});
if (registered) {
console.log('Service worker registered successfully');
// Send message to service worker
const response = await ServiceWorker.send({
type: 'CACHE_URLS',
urls: ['/api/data', '/api/user']
});
console.log('Service worker response:', response);
}
} else {
console.log('Service worker not supported');
}Storage interfaces and implementations for cross-platform compatibility.
/**
* Key-value storage interface
*/
interface KeyValueStorageInterface {
setItem(key: string, value: string): Promise<void> | void;
getItem(key: string): Promise<string | null> | string | null;
removeItem(key: string): Promise<void> | void;
clear(): Promise<void> | void;
}
/**
* Cookie-based storage implementation
*/
interface CookieStorage extends KeyValueStorageInterface {
setItem(key: string, value: string, options?: CookieOptions): void;
getItem(key: string): string | null;
removeItem(key: string): void;
clear(): void;
}
interface CookieOptions {
domain?: string;
expires?: Date;
httpOnly?: boolean;
maxAge?: number;
path?: string;
sameSite?: 'Strict' | 'Lax' | 'None';
secure?: boolean;
}
// Pre-configured storage instances
const defaultStorage: KeyValueStorageInterface;
const sessionStorage: KeyValueStorageInterface;
const sharedInMemoryStorage: KeyValueStorageInterface;Storage Examples:
import {
CookieStorage,
defaultStorage,
sessionStorage,
sharedInMemoryStorage
} from "aws-amplify/utils";
// Use default storage (localStorage in browser, AsyncStorage in React Native)
await defaultStorage.setItem('userPrefs', JSON.stringify({
theme: 'dark',
language: 'en'
}));
const prefs = await defaultStorage.getItem('userPrefs');
// Use session storage (cleared when tab closes)
sessionStorage.setItem('tempData', 'temporary value');
// Use cookie storage
const cookieStorage = new CookieStorage();
cookieStorage.setItem('sessionId', 'abc123', {
expires: new Date(Date.now() + 24 * 60 * 60 * 1000), // 24 hours
secure: true,
sameSite: 'Strict'
});
// Use in-memory storage (shared across components)
sharedInMemoryStorage.setItem('cache', JSON.stringify(data));Parse and validate Amplify configuration.
/**
* Parse Amplify configuration from various formats
* @param config - Configuration object to parse
* @returns Parsed ResourcesConfig
*/
function parseAmplifyConfig(
config: LegacyConfig | ResourcesConfig | AmplifyOutputs
): ResourcesConfig;
interface ResourcesConfig {
Auth?: AuthConfig;
API?: APIConfig;
Storage?: StorageConfig;
Analytics?: AnalyticsConfig;
Notifications?: NotificationsConfig;
}
interface LegacyConfig {
[key: string]: any;
}
interface AmplifyOutputs {
version: string;
auth?: any;
data?: any;
storage?: any;
custom?: any;
}Configuration Examples:
import { parseAmplifyConfig } from "aws-amplify/utils";
// Parse legacy configuration
const legacyConfig = {
Auth: {
region: 'us-east-1',
userPoolId: 'us-east-1_example',
userPoolWebClientId: 'exampleclientid'
}
};
const parsedConfig = parseAmplifyConfig(legacyConfig);
// Parse Amplify outputs format
const amplifyOutputs = {
version: '1',
auth: {
user_pool_id: 'us-east-1_example',
user_pool_client_id: 'exampleclientid',
identity_pool_id: 'us-east-1:example'
}
};
const modernConfig = parseAmplifyConfig(amplifyOutputs);// Hub event categories
type HubChannel =
| 'auth'
| 'api'
| 'analytics'
| 'storage'
| 'datastore'
| 'predictions'
| 'interactions'
| 'pubsub'
| 'core'
| string;
// Common utility types
interface Credentials {
accessKeyId: string;
secretAccessKey: string;
sessionToken?: string;
expiration?: Date;
}
interface Logger {
debug(message: string, ...args: any[]): void;
info(message: string, ...args: any[]): void;
warn(message: string, ...args: any[]): void;
error(message: string, ...args: any[]): void;
}
// Error types
class UtilsError extends Error {
name: 'UtilsError';
message: string;
cause?: Error;
}