Using BrightWeb Modules

Last updated

Source file

docs/modules/using-modules.md

This page explains how the shared BrightWeb modules are consumed in a generated app.

The shared modules are currently consumed through:

  • package entrypoints
  • generated scaffold wiring
  • server-side page helpers
  • shell registration objects
  • a small number of route handlers

Use this page together with the per-module pages when you need to answer both of these questions:

  1. What does this module install?
  2. How do I actually use it in an app?

Use Base Contract for the support-tier rules and base-contract.json when you need the canonical machine-readable inventory.

Integration model

In a generated platform app, module usage usually happens in 3 places:

  1. config/modules.ts decides which modules are enabled.
  2. config/shell.ts wires each enabled module registration into @brightweblabs/app-shell.
  3. App routes call the module package directly for server data, route handlers, or auth helpers.

That means BrightWeb module usage is primarily a package and wiring model. The stable base contract sits inside that model, but this page is focused on how those pieces get used in a real app.

Typical entrypoints

PackageTypical entrypointsSupport tierWhat you use them for
@brightweblabs/core-auth/sharedAUTH_RESEND_COOLDOWN_SECONDS, validateEmail(), validatePassword(), buildSignupCallbackUrl(), buildResetPasswordRedirectUrl()stableShared auth validation, constants, and URL derivation.
@brightweblabs/core-auth/clientuseCooldownTimer()stableClient-side auth UI behavior such as resend cooldowns.
@brightweblabs/core-auth/serverrequireServerPageAccess(), requireServerPageRoleAccess(), getServerAccess()stableServer-side auth and role gating in pages, layouts, and handlers.
@brightweblabs/infra/serverresendApiRequest(), verifyResendWebhookSignature(), getTransactionalSender(), getMarketingSender(), getContactDestination(), getResendWebhookSecret()stableCanonical app-owned Resend transport and webhook verification helpers.
@brightweblabs/infra/clientcreateBrowserSupabaseClient()stableBrowser Supabase client with BrightWeb environment resolution.
@brightweblabs/infra/realtimesubscribeToAppActivityEvents()stableAuthenticated, domain-filtered activity invalidation hints.
@brightweblabs/infra/request-observabilitycreateLatestRequestController(), observedFetch(), appendServerTiming()stableAbort stale collection requests and record privacy-safe client/server timing.
@brightweblabs/infra/robustnesspublicError(), readPublicError(), sanitizePublicError(), validateBoundedUuidBatch()stablePublic error envelopes and bounded mutation validation.
@brightweblabs/module-adminlistAdminUsers(), handleAdminUsersGetRequest(), handleAdminUsersRoleChangeRequest()stableReusable admin listing plus package-owned admin HTTP handlers.
@brightweblabs/module-admininvitation list/create/revoke/accept/registration helpers and handlersstableFourteen-day portal invitations for client, staff, and admin roles. Client invitations do not require an organization.
@brightweblabs/module-admingetAdminUsersPageData()starterStarter admin page payload for the scaffolded users screen.
@brightweblabs/module-admin/registrationadminModuleRegistrationstableAdmin app-shell navigation and toolbar registration.
@brightweblabs/module-admin/uiAdminUsersClient, AdminToolbarControls, createAdminUiClient()stablePackaged users, roles, invitations, and shell toolbar UI with injectable data access.
@brightweblabs/module-admin/tokens.cssAdmin UI tokens and parity classesstableRequired visual contract for the packaged Admin UI.
@brightweblabs/module-orgslistOrganizations(), createOrganization(), updateOrganization(), listOrganizationMembers(), setOrganizationMemberRole()stableShared organization and membership data operations used by CRM and Projects.
@brightweblabs/module-orgs/uiOrganizationCreateSheetstableShared organization-creation sheet with optional member invitations for CRM, Projects, and app-owned flows.
@brightweblabs/module-orgs/registrationorgsModuleRegistrationstableHidden foundation registration with no navigation.
@brightweblabs/module-crmlistCrmContacts(), listCrmOrganizations(), getCrmContactStatusStats(), listCrmOwnerOptions(), listCrmPrimaryContacts(), listCrmStatusTimeline()stableReusable CRM primitives for package-owned CRM surfaces and workflows.
@brightweblabs/module-crmhandleCrmContactsGetRequest(), handleCrmOrganizationsGetRequest(), handleCrmStatsGetRequest(), handleCrmOwnersGetRequest()stablePackage-owned CRM GET handlers that can be mounted directly from Next.js routes.
@brightweblabs/module-crmgetCrmDashboardData()starterStarter CRM dashboard payload for the scaffolded CRM page.
@brightweblabs/module-crm/registrationcrmModuleRegistrationstableCRM app-shell navigation groups and toolbar registration.
@brightweblabs/module-marketingcampaign, workflow, analytics, webhook, and handler-composition helpersstableConsent-aware marketing domain behavior and package-owned HTTP composition.
@brightweblabs/module-marketing/servertopics, subscriptions, suppressions, and unsubscribe helpersstableConsent and contact communication preferences.
@brightweblabs/module-marketing/campaignscampaign CRUD, recipient expansion, scheduling, sending, retry, and test deliverystableCampaign lifecycle and delivery orchestration.
@brightweblabs/module-marketing/uiMarketingClient, MarketingUiProvider, createMarketingUiClient(), MarketingToolbarControlsstarterPackage-owned marketing workspace with injectable data access.
@brightweblabs/module-marketing/registrationmarketingModuleRegistrationstableMarketing navigation and toolbar registration.
@brightweblabs/module-projectslistProjects(), getProjectPortfolioStats(), getProjectDashboard(), listProjectTasks(), listProjectMilestones(), listProjectLinks(), listClientProjects(), getClientProject()stableReusable internal project workspaces plus narrow client-safe account reads.
@brightweblabs/module-projectscreateProject(), createProjectOrganization(), updateProject(), deleteProject(), createProjectTask(), updateProjectTask(), deleteProjectTask(), createProjectMilestone(), updateProjectMilestone(), deleteProjectMilestone(), createProjectLink(), updateProjectLink(), deleteProjectLink(), listProjectAssignableProfiles(), syncProjectMembers(), listOrgAdminProjectsByProfile()stableApp-owned project write flows and assignment helpers.
@brightweblabs/module-projectsgetProjectsPortfolioPageData()starterStarter portfolio payload for the scaffolded projects page.
@brightweblabs/module-projects/registrationprojectsModuleRegistrationstableProjects app-shell navigation and toolbar registration.

For the full symbol-level classification, including internal exports that are visible in source but not part of the supported promise, use base-contract.json.

Common usage patterns

1. Read module data in a server route or page

The current starters call the module packages directly from server pages.

TSX
export const dynamic = "force-dynamic";

export default async function CrmPage() {
  const { getCrmDashboardData } = await import("@brightweblabs/module-crm");
  const data = await getCrmDashboardData();

  return <pre>{JSON.stringify(data.stats, null, 2)}</pre>;
}

The same pattern exists for the Projects and Admin starters:

TSX
const { getProjectsPortfolioPageData } = await import("@brightweblabs/module-projects");
const portfolio = await getProjectsPortfolioPageData();
TSX
import { requireServerPageRoleAccess } from "@brightweblabs/core-auth/server";

export default async function ProjectPage({ params }: { params: { projectId: string } }) {
  const { supabase } = await requireServerPageRoleAccess(["admin", "staff"]);
  const { getProjectDashboard } = await import("@brightweblabs/module-projects");
  const project = await getProjectDashboard(supabase, params.projectId);

  return <pre>{JSON.stringify(project.project, null, 2)}</pre>;
}
TSX
const { getAdminUsersPageData } = await import("@brightweblabs/module-admin");
const { users } = await getAdminUsersPageData();

Use these helpers when you want the package to own the initial query and normalization logic. Then build your own UI on top of the returned data.

If you need a longer-lived reusable surface, prefer the stable helpers from the manifest over starter page helpers.

For CRM specifically, the stable path is now the smaller helper set:

TS
const [contacts, organizations, stats, owners] = await Promise.all([
  listCrmContacts(supabase, { page: 1, pageSize: 50 }),
  listCrmOrganizations(supabase, { page: 1, pageSize: 20 }),
  getCrmContactStatusStats(supabase),
  listCrmOwnerOptions(supabase),
]);

2. Register module navigation and toolbar behavior in the shell

If your app uses @brightweblabs/app-shell, wire the module registrations into your shell config.

TS
import type { ShellContextualAction, ShellModuleRegistration } from "@brightweblabs/app-shell";
import { crmModuleRegistration } from "@brightweblabs/module-crm/registration";
import { marketingModuleRegistration } from "@brightweblabs/module-marketing/registration";
import { projectsModuleRegistration } from "@brightweblabs/module-projects/registration";
import { adminModuleRegistration } from "@brightweblabs/module-admin/registration";

const dashboardModuleRegistration: ShellModuleRegistration<ShellContextualAction> = {
  key: "dashboard",
  placement: "primary",
  navItems: [{ href: "/dashboard", label: "Dashboard" }],
};

const modules = [
  dashboardModuleRegistration,
  crmModuleRegistration,
  marketingModuleRegistration,
  projectsModuleRegistration,
  adminModuleRegistration,
];

This is the current mechanism for getting module-owned nav items, nav groups, and toolbar route/action registration into the platform shell.

The CRM dashboard follows the MQ shell contract: search, filters, and create actions are not duplicated inside the page. Render CrmToolbarControls for the crm toolbar surface (or compose the exported CrmToolbarSearchChip, CrmToolbarFiltersPill, and CrmToolbarCreateMenu controls individually). A standalone CrmDashboard remains usable for table, dialog, timeline, and organization interactions, but its shell-owned search/filter/create controls are intentionally absent.

3. Mount starter API routes by delegating to package handlers

Admin and CRM expose route-handler helpers that can be re-exported from your Next.js route files.

TS
export const dynamic = "force-dynamic";

export async function GET(request: Request) {
  const { handleAdminUsersGetRequest } = await import("@brightweblabs/module-admin");
  return handleAdminUsersGetRequest(request);
}
TS
export const dynamic = "force-dynamic";

export async function POST(request: Request) {
  const { handleAdminUsersRoleChangeRequest } = await import("@brightweblabs/module-admin");
  return handleAdminUsersRoleChangeRequest(request);
}

Use this pattern when a package already owns the HTTP handling contract and your app just needs to mount it under a route.

CRM follows the same pattern:

TS
export const dynamic = "force-dynamic";

export async function GET(request: Request) {
  const { handleCrmContactsGetRequest } = await import("@brightweblabs/module-crm");
  return handleCrmContactsGetRequest(request);
}

The current CRM starter mounts these package-owned GET handlers at:

  • /api/crm/contacts
  • /api/crm/organizations
  • /api/crm/stats
  • /api/crm/owners

4. Consume auth from the shared, client, and server entrypoints

The auth package is intentionally split by runtime.

Shared helpers

TS
import {
  AUTH_RESEND_COOLDOWN_SECONDS,
  buildResetPasswordRedirectUrl,
  buildSignupCallbackUrl,
  validateEmail,
  validatePassword,
} from "@brightweblabs/core-auth/shared";

Client hooks

TSX
import { useCooldownTimer } from "@brightweblabs/core-auth/client";

const cooldown = useCooldownTimer(AUTH_RESEND_COOLDOWN_SECONDS);

Server guards

TS
import { requireServerPageAccess, requireServerPageRoleAccess } from "@brightweblabs/core-auth/server";

const { supabase, user, profileId } = await requireServerPageAccess();
const adminAccess = await requireServerPageRoleAccess("admin");

Use shared for runtime-independent logic, client for React hooks, and server for page and route protection.

5. Use infra transport helpers for app-owned email flows

For app-owned email behavior (contact forms, invites, campaigns, and webhook verification), use @brightweblabs/infra/server.

TS
import {
  getMarketingSender,
  resendApiRequest,
  verifyResendWebhookSignature,
} from "@brightweblabs/infra/server";

Auth email flows should stay on supabase.auth.* and Supabase Auth SMTP/project settings.

Module-specific usage notes

Platform Base

  • Use @brightweblabs/core-auth/server to gate pages and get the current signed-in user context.
  • Use @brightweblabs/core-auth/shared for validation and callback URL helpers.
  • Use @brightweblabs/module-admin for admin user listing, role changes, handlers, and the mountable AdminUsersPage.
  • Use @brightweblabs/module-admin/ui when an app needs to inject its own users/invitations client or compose AdminToolbarControls into AppHeader.

CRM

  • Build on listCrmContacts(), getCrmContactStatusStats(), listCrmStatusTimeline(), listCrmPrimaryContacts(), and listCrmOwnerOptions() when you need reusable CRM data primitives.
  • Import listOrganizations() from @brightweblabs/module-orgs for new organization lists; listCrmOrganizations() remains as a compatibility alias.
  • Load only the CRM slices a page needs. For example, a contacts-first page can skip listCrmOwnerOptions() and listCrmPrimaryContacts() until an assignment or organization-edit workflow needs them.
  • Mount the package-owned CRM GET handlers when you want the package to own the initial HTTP contract.
  • Treat getCrmDashboardData() as starter page glue for the scaffolded CRM screen.
  • Build reusable forms, tables, actions, and workflows in the CRM package, then keep the app route as a thin mount.

Marketing

  • Mount MarketingPage for the complete staff workspace or inject createMarketingUiClient() into package UI surfaces.
  • Keep Resend credentials, worker secrets, and webhook secrets in the generated server-only _handlers.ts composition.
  • Use the domain subpaths for custom products: /server for consent, /campaigns for campaign lifecycle, /segments for audiences, /worker for bounded delivery, and /email for the injected sender.
  • Treat the generated worker, webhook, and unsubscribe routes as one operational unit; a campaign UI without those routes is not a complete delivery installation.
  • Follow Marketing Delivery & Scheduler before enabling production sends.

Projects

  • Build on listProjects() and getProjectPortfolioStats() when you need reusable project listing and metrics helpers.
  • Use getProjectDashboard() for internal detail views. Client-facing routes must use listClientProjects() and getClientProject(); never project the full internal dashboard into a client response.
  • Use the task, milestone, link, and member helpers when your app owns project write flows.
  • Treat getProjectsPortfolioPageData() as starter package glue. New scaffolds mount package-owned Projects UI through @brightweblabs/module-projects/routes; host apps can use those route components directly or build custom pages on the lower-level helpers.
  • Use @brightweblabs/module-projects/route-handlers for thin generated API routes and the package-root handle*Request() exports when composing host-owned request behavior.
  • Use projectsModuleRegistration when you want project navigation and toolbar behavior in the shell.

Related contract docs

  • Base Contract defines the support tiers.
  • base-contract.json is the canonical symbol inventory.
  • The module pages explain what each module installs, what is stable, and what is only starter scaffolding.

Related docs

Implementation references

  • packages/core-auth/src/shared.ts
  • packages/core-auth/src/client.ts
  • packages/core-auth/src/server.ts
  • packages/module-admin/src/index.ts
  • packages/module-admin/src/registration.ts
  • packages/module-crm/src/index.ts
  • packages/module-crm/src/registration.ts
  • packages/module-projects/src/index.ts
  • packages/module-projects/src/registration.ts
  • packages/create-bw-app/template/modules/admin/app/api/admin/users/route.ts
  • packages/create-bw-app/template/modules/admin/app/api/admin/users/roles/route.ts
  • packages/create-bw-app/template/modules/crm/app/api/crm/contacts/route.ts
  • packages/create-bw-app/template/modules/crm/app/api/crm/organizations/route.ts
  • packages/create-bw-app/template/modules/crm/app/api/crm/stats/route.ts
  • packages/create-bw-app/template/modules/crm/app/api/crm/owners/route.ts
  • packages/create-bw-app/template/modules/admin/app/admin/users/page.tsx
  • packages/create-bw-app/template/modules/crm/app/crm/page.tsx
  • apps/platform-preview/config/shell.ts