Skip to main content

Lib Utilities Overview

The template/lib/ directory is the core utility and business logic layer of the Ever Works Template. It contains shared modules for analytics, API communication, authentication, background jobs, caching, configuration, database access, payments, editor tooling, guards, and more. All non-component, non-route logic lives here following the principle of keeping components presentational and delegating heavy logic to lib/.

Module Map

Directory Structure

Directory / FileDescription
lib/analytics/PostHog + Sentry analytics singleton (docs)
lib/api/HTTP clients for browser and server (docs)
lib/auth/Authentication with NextAuth.js + Supabase (docs)
lib/background-jobs/Job scheduling with Trigger.dev / local / no-op (docs)
lib/cache-config.tsCache TTL and tag definitions (docs)
lib/cache-invalidation.tsCache invalidation functions (docs)
lib/config/Centralized configuration service with Zod schemas
lib/config.tsSite configuration (siteConfig)
lib/config-manager.tsRuntime configuration manager
lib/constants.tsApplication constants barrel (docs)
lib/constants/Domain-specific constants (payment, analytics)
lib/content.tsGit-based CMS content loading and caching
lib/db/Database connection, migrations, seeding, queries (docs)
lib/editor/TipTap rich text editor components and utilities (docs)
lib/guards/Plan-based feature access control (docs)
lib/helpers.tsLanguage code to country code mapping
lib/lib.tsContent path resolution, file system utilities
lib/logger.tsStructured logging utility
lib/mail/Email sending with template support
lib/mappers/Data transformation mappers
lib/maps/Map provider integrations (Google Maps, Mapbox)
lib/middleware/Next.js middleware utilities
lib/newsletter/Newsletter subscription providers
lib/paginate.tsPagination helper function
lib/payment/Payment processing (Stripe, LemonSqueezy, Solidgate, Polar)
lib/permissions/Role-based permission definitions
lib/query-client.tsReact Query client configuration
lib/react-query-config.tsReact Query default options
lib/repositories/Data access layer (repository pattern)
lib/repository.tsGit repository operations (clone, pull, sync)
lib/seo/SEO metadata and structured data generators
lib/services/Business logic services (20+ domain services)
lib/stripe-helpers.tsStripe-specific utilities
lib/swagger/Swagger/OpenAPI annotations
lib/theme-color-manager.tsDynamic theme color management
lib/theme-utils.tsTheme utility functions
lib/themes.tsxTheme definitions
lib/types.tsShared type definitions
lib/types/Domain-specific type definitions
lib/utils.tsGeneral utility functions
lib/utils/Domain-specific utilities (15+ modules)
lib/validations/Zod validation schemas

Key Standalone Modules

lib/helpers.ts -- Language/Country Code Mapping

type LanguageCode = 'en' | 'fr' | 'es' | 'zh' | 'de' | 'ar' | ... ;

const LANGUAGE_COUNTRY_CODES: Record<LanguageCode, string>;
// { en: 'US', fr: 'FR', es: 'ES', zh: 'CN', ... }

const appLocales: string[];
// All supported locale codes

function getCountryCode(languageCode?: LanguageCode): string;
// 'en' -> 'US', 'fr' -> 'FR'

lib/lib.ts -- Content Path and File System

Server-only utilities for content directory management:

function getContentPath(): string;
// Returns '.content' path (local) or '/tmp/.content' (Vercel runtime)

async function ensureContentAvailable(): Promise<string>;
// Ensures content is available, triggering Git clone if needed

async function fsExists(filepath: string): Promise<boolean>;
async function dirExists(dirpath: string): Promise<boolean>;

lib/paginate.ts -- Pagination Helper

function paginate<T>(items: T[], page: number, limit: number): T[];

lib/logger.ts -- Structured Logging

const logger = {
info(message: string, context?: Record<string, any>): void;
warn(message: string, context?: Record<string, any>): void;
error(message: string, context?: Record<string, any>): void;
debug(message: string, context?: Record<string, any>): void;
};

lib/color-generator.ts -- Deterministic Color Generation

Generates consistent colors from strings (used for avatars, tags, etc.).

lib/theme-color-manager.ts -- Dynamic Theme Colors

Manages CSS custom property updates for theme switching.

Services Layer (lib/services/)

The services directory contains business logic services organized by domain:

ServiceResponsibility
analytics-background-processor.tsBackground analytics processing
analytics-export.service.tsAnalytics data export
analytics-scheduled-reports.service.tsScheduled analytics reports
category-file.service.tsCategory file operations
category-git.service.tsCategory Git operations
collection-git.service.tsCollection Git operations
company.service.tsCompany profile management
currency-detection.service.tsUser currency detection
currency.service.tsCurrency conversion
email-notification.service.tsEmail notifications
engagement.service.tsView/vote/favorite tracking
file.service.tsFile upload/management
geocoding/Geocoding with Google/Mapbox providers
item-audit.service.tsItem audit trail
item-git.service.tsItem Git operations
location/Location indexing and management
moderation.service.tsContent moderation
notification.service.tsPush notifications
posthog-api.service.tsServer-side PostHog API
role-db.service.tsRole management
settings.service.tsApplication settings
sponsor-ad.service.tsSponsor ad management
stripe-products.service.tsStripe product sync
subscription-jobs.tsSubscription background jobs
subscription.service.tsSubscription lifecycle
survey.service.tsSurvey management
sync-service.tsGit repository synchronization
tag-git.service.tsTag Git operations
twenty-crm-*.tsTwenty CRM integration (5 files)
user-db.service.tsUser database operations
webhook-subscription.service.tsWebhook management

Utils Layer (lib/utils/)

Utility modules for specific concerns:

ModulePurpose
api-error.tsAPI error class
bot-detection.tsBot user-agent detection
checkout-utils.tsPayment checkout helpers
client-auth.tsClient-side auth utilities
currency-format.tsCurrency formatting
custom-navigation.tsCustom router navigation
database-check.tsDatabase health check
email-validation.tsEmail format validation
error-handler.tsGlobal error handler
featured-items.tsFeatured item selection
footer-utils.tsFooter link utilities
image-domains.tsAllowed image domains
pagination-validation.tsPagination param validation
payment-provider.tsPayment provider detection
plan-expiration.utils.tsPlan expiration calculations
rate-limit.tsAPI rate limiting
request-body.tsRequest body parsing
server-url.tsServer URL resolution
settings.tsSettings helper functions
slug.tsURL slug generation
url-cleaner.tsURL sanitization
url-filter-sync.tsURL filter state sync

Design Principles

  1. Separation of Concerns -- Business logic in services/, data access in repositories/ and db/queries/, presentation in components/.

  2. Script Safety -- Modules used by migration/seed scripts (like constants/payment.ts and db/config.ts) avoid importing Next.js-specific code.

  3. Lazy Initialization -- Database connections, API clients, and job managers use singleton patterns with lazy initialization to avoid errors during build time.

  4. Dynamic Imports -- Node.js-specific modules use dynamic imports in background jobs and auth to prevent webpack bundling issues.

  5. Server/Client Boundary -- Server-only modules use the server-only package. Client-safe modules avoid server imports. The 'use client' directive is used sparingly.