Skip to Content

Lib Documentation

Overview

The lib directory (src/lib/) contains utility functions, configurations, and shared logic that doesn’t fit into components or services. This includes analytics setup, authentication configuration, custom hooks, and third-party service integrations.

Directory Structure

src/lib/ ├── analytics/ # Analytics integrations │ ├── google-analytics.ts │ └── vercel-analytics.ts ├── hooks/ # Custom React hooks │ ├── beneficiary-enrollment/ │ ├── client-class/ │ ├── client-company/ │ ├── company-insurance-provider/ │ ├── hr/ │ ├── insurance-company/ │ ├── manage-insurance-state/ │ ├── principal/ │ ├── tabs-data/ │ ├── use-audit-actions.ts │ ├── use-auto-logout.ts │ ├── use-countdown.ts │ ├── use-data-logs-filter.ts │ ├── use-local-storage.ts │ ├── use-params.ts │ └── use-refresh-token.ts ├── auth-options.ts # NextAuth configuration ├── excel-js.ts # Excel export (exceljs) ├── excel.ts # Excel utilities ├── sentry.ts # Sentry error tracking └── toast.ts # Toast notifications

Analytics (lib/analytics/)

Analytics integrations for tracking user behavior and application performance.

Google Analytics (analytics/google-analytics.ts)

Google Analytics 4 integration:

// Key exports export function trackEvent(eventName: string, params?: Record<string, unknown>): void; export function trackPageView(path: string): void; export function initializeGA(gaId: string): void;

Usage:

import { trackEvent, trackPageView } from '@/lib/analytics/google-analytics'; // Track custom event trackEvent('beneficiary_enrolled', { provider: 'Cocolife', plan_type: 'premium', }); // Track page view trackPageView('/dashboard/beneficiaries');

Vercel Analytics (analytics/vercel-analytics.ts)

Vercel Web Analytics integration:

export function useVercelAnalytics(): void;

Setup: Automatically initialized in _app.tsx for production builds.


Authentication (lib/auth-options.ts)

NextAuth.js configuration with credentials provider and OTP authentication.

Key Configuration

export const authOptions: NextAuthOptions = { providers: [ CredentialsProvider({ name: 'Credentials', credentials: { email: { label: 'Email', type: 'email' }, otp: { label: 'OTP', type: 'text' }, workspace: { label: 'Workspace', type: 'text' }, }, async authorize(credentials) { // OTP verification logic }, }), ], callbacks: { async jwt({ token, user }) { // Token refresh logic }, async session({ session, token }) { // Session augmentation }, }, pages: { signIn: '/', error: '/', }, };

Features

  • OTP-based login - One-time password authentication
  • Workspace validation - Validates ?workspace= parameter
  • JWT token management - Automatic refresh and session handling
  • Role-based access - Broker, Principal, Beneficiary roles

Usage:

import { authOptions } from '@/lib/auth-options'; import { getServerSession } from 'next-auth/next'; // Server-side session const session = await getServerSession(authOptions); // Client-side (useSession from next-auth/react) const { data: session, status } = useSession();

Error Tracking (lib/sentry.ts)

Sentry configuration for error monitoring and performance tracking.

Configuration

export function initializeSentry(dsn: string): void; export function captureException(error: Error, context?: Record<string, unknown>): void; export function captureMessage(message: string, level?: SeverityLevel): void; export function setUser(user: { id: string; email: string } | null): void;

Features:

  • Error capture with context
  • User identification for error tracking
  • Performance monitoring
  • Release tracking

Usage:

import { captureException, setUser } from '@/lib/sentry'; try { await riskyOperation(); } catch (error) { captureException(error, { component: 'BeneficiaryForm', action: 'submit_enrollment', }); } // Set user for error context setUser({ id: session.user.id, email: session.user.email });

Configuration Files:

  • sentry.edge.config.ts - Edge runtime config
  • sentry.server.config.ts - Server-side config
  • Client config in instrumentation-client.ts

Toast Notifications (lib/toast.ts)

Sonner toast notification utilities.

API

export function toast(options: ToastOptions): void; export function success(message: string, options?: ToastOptions): void; export function error(message: string, options?: ToastOptions): void; export function warning(message: string, options?: ToastOptions): void; export function info(message: string, options?: ToastOptions): void; export function promise<T>( promise: Promise<T>, messages: { loading: string; success: string; error: string; } ): Promise<T>;

Usage:

import { toast, success, error, promise } from '@/lib/toast'; // Simple toast toast({ title: 'Hello', description: 'World' }); // Typed toasts success('Beneficiary enrolled successfully'); error('Failed to save changes'); // Promise toast await promise( fetch('/api/enroll'), { loading: 'Enrolling...', success: 'Enrollment complete!', error: 'Enrollment failed', } );

Excel Export (lib/excel-js.ts, lib/excel.ts)

Utilities for generating and downloading Excel files.

Excel JS (lib/excel-js.ts)

Using exceljs for advanced Excel generation:

export function createWorkbook(): Workbook; export function addWorksheet(workbook: Workbook, name: string): Worksheet; export function addStyledRow(worksheet: Worksheet, data: unknown[], styles?: CellStyle): void; export function downloadExcel(workbook: Workbook, filename: string): void;

Excel Utils (lib/excel.ts)

Simplified Excel operations:

export function exportToExcel(data: unknown[], filename: string): void; export function formatExcelDate(date: Date): string; export function setColumnWidths(worksheet: Worksheet, widths: number[]): void;

Usage:

import { createWorkbook, downloadExcel } from '@/lib/excel-js'; import { exportToExcel } from '@/lib/excel'; // Quick export exportToExcel(membersData, 'members.xlsx'); // Advanced with styling const workbook = createWorkbook(); const sheet = addWorksheet(workbook, 'Members'); addStyledRow(sheet, ['Name', 'Email', 'Status'], { font: { bold: true }, fill: { type: 'pattern', pattern: 'solid', fgColor: { argb: 'CCCCCC' } }, }); downloadExcel(workbook, 'members-report.xlsx');

Custom Hooks (lib/hooks/)

Reusable React hooks organized by domain.

Hook Categories

DirectoryPurposeHooks
beneficiary-enrollment/Enrollment workflows4 hooks
client-class/Client classification9 hooks
client-company/Company management8 hooks
company-insurance-provider/Provider associations3 hooks
hr/HR portal4 hooks
insurance-company/Provider data2 hooks
manage-insurance-state/Insurance state2 hooks
principal/Principal portal2 hooks
tabs-data/Tab management2 hooks

Common Hooks

useAuditActions (use-audit-actions.ts)

Track user actions for audit logging:

export function useAuditActions() { return { logAction: (action: string, metadata?: Record<string, unknown>) => void; logView: (entity: string, id: string) => void; logCreate: (entity: string, data: unknown) => void; logUpdate: (entity: string, id: string, changes: unknown) => void; logDelete: (entity: string, id: string) => void; }; }

Usage:

import { useAuditActions } from '@/lib/hooks/use-audit-actions'; const { logAction, logUpdate } = useAuditActions(); // Log custom action logAction('export_members', { provider: 'Cocolife', count: 50 }); // Log entity update logUpdate('beneficiary', id, { status: 'approved' });

useAutoLogout (use-auto-logout.ts)

Automatic session timeout management:

export function useAutoLogout(options?: { timeout?: number; // ms before logout (default: 30 min) warningThreshold?: number; // ms before warning (default: 5 min) onWarning?: () => void; onLogout?: () => void; }): { remainingTime: number; isWarning: boolean; resetTimer: () => void; };

Usage:

import { useAutoLogout } from '@/lib/hooks/use-auto-logout'; function App() { const { remainingTime, isWarning, resetTimer } = useAutoLogout({ timeout: 30 * 60 * 1000, // 30 minutes onWarning: () => toast.warning('Session expiring soon...'), onLogout: () => signOut(), }); // Reset on user activity useEffect(() => { const handleActivity = () => resetTimer(); window.addEventListener('mousemove', handleActivity); window.addEventListener('keydown', handleActivity); return () => { window.removeEventListener('mousemove', handleActivity); window.removeEventListener('keydown', handleActivity); }; }, [resetTimer]); }

useCountdown (use-countdown.ts)

Countdown timer hook:

export function useCountdown(initialSeconds: number): { seconds: number; isActive: boolean; start: () => void; pause: () => void; reset: () => void; };

Usage:

import { useCountdown } from '@/lib/hooks/use-countdown'; function OTPInput() { const { seconds, isActive, start } = useCountdown(60); return ( <div> <p>Resend in {seconds}s</p> <Button onClick={start} disabled={isActive}> Resend OTP </Button> </div> ); }

useLocalStorage (use-local-storage.ts)

Synced localStorage hook:

export function useLocalStorage<T>( key: string, initialValue: T ): [T, (value: T | ((prev: T) => T)) => void, () => void];

Usage:

import { useLocalStorage } from '@/lib/hooks/use-local-storage'; function Settings() { const [theme, setTheme] = useLocalStorage('theme', 'light'); const [filters, setFilters] = useLocalStorage('dashboard-filters', {}); return ( <select value={theme} onChange={e => setTheme(e.target.value)}> <option value="light">Light</option> <option value="dark">Dark</option> </select> ); }

useParams (use-params.ts)

Enhanced URL params hook with type safety:

export function useParams<T extends Record<string, string>>(): T; export function useParam(key: string): string | undefined; export function useQueryParams(): URLSearchParams;

useRefreshToken (use-refresh-token.ts)

Automatic token refresh management:

export function useRefreshToken(): { refresh: () => Promise<string>; isRefreshing: boolean; };

Creating New Lib Files

New Hook Pattern

// lib/hooks/use-my-feature.ts import { useState, useEffect } from 'react'; interface UseMyFeatureOptions { enabled?: boolean; onSuccess?: (data: unknown) => void; } export function useMyFeature(options: UseMyFeatureOptions = {}) { const [data, setData] = useState<unknown>(null); const [isLoading, setIsLoading] = useState(false); useEffect(() => { if (!options.enabled) return; setIsLoading(true); fetchData() .then(result => { setData(result); options.onSuccess?.(result); }) .finally(() => setIsLoading(false)); }, [options.enabled]); return { data, isLoading }; }

New Utility Pattern

// lib/my-utility.ts export interface MyUtilityOptions { retries?: number; timeout?: number; } export async function myUtility( input: string, options: MyUtilityOptions = {} ): Promise<Result> { const { retries = 3, timeout = 5000 } = options; // Implementation }

Best Practices

  1. Hooks start with use - Follow React naming convention
  2. Export types - Always export relevant TypeScript types
  3. Document with JSDoc - Describe parameters and return values
  4. Handle cleanup - Return cleanup functions from effects
  5. Error handling - Wrap async operations in try-catch
  6. Default values - Provide sensible defaults for options

Last updated on