<>ts-stack
Get StartedArchitecturePackagesSpecsGuides
⌘K
Reference
Home
Get StartedOverviewInstallChoose your stackKey concepts
ArchitectureOverviewStack layersBEEF (BRC-62)BRC-100 Wallet InterfaceIdentity & AuthConformance pipeline
PackagesOverviewSDKWalletNetworkOverlays
@bsv/overlay@bsv/overlay-express@bsv/overlay-topics@bsv/overlay-discovery-services@bsv/eqc@bsv/gasp@bsv/btms-backend
MessagingMiddlewareHelpers
InfrastructureOverviewmessage-box-serveroverlay-serveruhrp-server-basicuhrp-server-cloud-bucketwabwallet-infrachaintracks-serverwebrtpay-relay
SpecsOverviewBRC-100 Wallet InterfaceOverlay HTTPMessage-box HTTPAuthsocket (WebSocket)BRC-31 Auth HandshakeBRC-29 Peer PaymentBRC-121 / HTTP 402ARC BroadcastMerkle ServiceStorage AdapterGASP SyncUHRPAir-Gap Optical (BRC-141)
ConformanceOverviewVector catalogTS runnerContributing vectors
GuidesOverviewIdentity, DIDs and credentialsIdentity migrationBuild a wallet-aware appRun an overlay nodePeer-to-peer messagingHTTP 402 payments
ReferenceOverviewBRC indexRepository health
AboutVersioningContributingDoc agentDocumentation sources
npm@bsv/overlay-expressv2.9.1API reference (TypeDoc) ↗
Loading…
Edit this page on GitHub
© 2026 BSV Blockchain. ts-stack is open-source.
GitHubContributingVersioning

@bsv/overlay-express

This source candidate declares SDK peer ^2.4.0 || ^3.0.0 || ^4.0.1. SDK3 remains a coordinated proposal; see the qualification and migration limits before adopting it.

Opinionated Express.js HTTP server wrapper for @bsv/overlay with built-in configuration, health checks, and peer discovery.

Install

bash
npm install @bsv/overlay-express

Quick start

typescript
import OverlayExpress from '@bsv/overlay-express'

const server = new OverlayExpress('testnode', process.env.SERVER_PRIVATE_KEY!, 'example.com')

server.configurePort(8080)
await server.configureKnex(process.env.KNEX_URL!)
await server.configureMongo(process.env.MONGO_URL!)

server.configureTopicManager('tm_helloworld', new HelloWorldTopicManager())
await server.configureLookupServiceWithMongo('ls_helloworld', mongoDb =>
  createHelloWorldLookupService(mongoDb)
)

await server.configureEngine()
await server.start()

process.once('SIGTERM', () => void server.close())
process.once('SIGINT', () => void server.close())

What it provides

  • OverlayExpress — One-stop configuration for building an overlay HTTP server
  • Configuration methods — Simple fluent API for Knex, MongoDB, topic managers, lookup services
  • Health endpoints — /health/live, /health/ready, /health with custom checks
  • Admin token — Bearer token authentication for protected endpoints
  • Web UI — Auto-generated documentation and service explorer
  • BanService — Optional output banning by txid.outputIndex
  • JanitorService — Health validation for SHIP/SLAP peer hosts
  • Provider chain — Arcade-first broadcast/proof lookup with Arc fallback
  • Chaintracks integration — Header resolution and reorg SSE for BASM
  • OverlayMonitor — Lookup probes plus optional admin maintenance actions
  • Graceful lifecycle — Idempotent close() drains HTTP and closes background work and databases

Progressive and live lookup candidate

The optional @bsv/overlay-express/root-eviction-response entry connects authenticated response queueing to a durable root-advertisement journal. guardRootAdvertisementResponse requires middleware 2.3.0, SDK 3.3.0, a revision captured before hydration, every disclosed target and current synchronous data/control access checks. It resets a stale response in full and separately fences the signed replacement. It does not mount routes or automatically guard existing serving paths. See root coordination.

The optional @bsv/overlay-express/root-eviction entry exposes createRootEvictionRouter for explicit request/status integration. A shared RootEvictionService and durable journal preserve received bytes, original selection and final current access through packet and HTTP signing. Wildcard credential-free CORS remains the default; exact origin lists are opt-in. Mount before generic parsers with the origin's actual shared authentication middleware. Alternatively, call configureRootEviction before start() with the server's wallet identity. The host shares authentication, mounts the handshake once, inherits its browser policy and clamps byte limits to host bounds. The application retains journal and worker lifecycle ownership. Capabilities, scheduling and complete serving/admission/GASP enforcement still require separate integration; no existing route is changed automatically.

The unpublished 2.8.0 candidate adds configureOutputLookup and the separate @bsv/overlay-express/output-lookup entry. Supply a durable companion service, signed capability identity, chain and explicit allowed browser origins before starting the host. The opt-in routes share authentication and enforce their own framing, selection, byte and physical-work limits. The host leaves injected provider database ownership with the application.

The durable lookup guide explains the provider, SQLite recovery, current authorization and mounting rules. The feature requires SDK 3.3.0; legacy root imports and finite routes remain available without enabling it. The candidate is not a package publication or a claim of complete application qualification.

Common patterns

Basic server setup

typescript
const server = new OverlayExpress('mynode', privateKey, 'mynode.example.com')

server.configurePort(3000)
await server.configureKnex('postgresql://user:pass@localhost/db')

Register multiple topics

Register services only under an explicit operator choice. The existing identity pair serves attributed public certificates under BRC-189 semantics; discovery of its host does not establish issuer trust. Identity-key DID resolution is local and deterministic. The serial-token DID overlay is removed in the proposed @bsv/overlay-topics 2.0 release; see the migration guide.

typescript
import { IdentityTopicManager, createIdentityLookupService } from '@bsv/overlay-topics'

server.configureTopicManager('tm_helloworld', new HelloWorldTopicManager())
server.configureTopicManager('tm_kvstore', new KVStoreTopicManager())
server.configureTopicManager('tm_identity', new IdentityTopicManager())

await server.configureLookupServiceWithMongo('ls_helloworld', db =>
  createHelloWorldLookupService(db)
)
await server.configureLookupServiceWithMongo('ls_kvstore', db => createKVStoreLookupService(db))
await server.configureLookupServiceWithMongo('ls_identity', db => createIdentityLookupService(db))

await server.configureEngine()
await server.start()

Configure health checks

typescript
server.configureHealth({
  contextProvider: async () => ({
    deployment: 'my-overlay',
    network: 'main'
  })
})

server.registerHealthCheck({
  name: 'custom-cache',
  critical: false,
  handler: async () => ({
    status: 'ok',
    details: { warmed: true }
  })
})

Advanced engine options

typescript
server.configureEngineParams({
  logTime: true,
  throwOnBroadcastFailure: true,
  suppressDefaultSyncAdvertisements: false
})

server.configureEnableGASPSync(true)
server.configureArcade(process.env.ARCADE_URL!, {
  apiKey: process.env.ARCADE_API_KEY,
  deploymentId: process.env.ARCADE_DEPLOYMENT_ID
})
server.configureArcApiKey(process.env.ARC_API_KEY!)
server.configureChaintracks(process.env.CHAINTRACKS_URL ?? process.env.ARCADE_URL!, {
  apiPrefix: '/chaintracks/v2',
  reorgStream: true,
  scanDepth: 3
})
server.configureEnableBASMSync(true)
server.configureUnprovenMaintenance({
  thresholdBlocks: 144,
  intervalMs: 60 * 60 * 1000
})
server.configureWebUI({
  host: 'https://example.com',
  primaryColor: '#ff0000'
})

Monitor an overlay deployment

typescript
import { OverlayMonitor } from '@bsv/overlay-express'

const monitor = new OverlayMonitor({
  intervalMs: 60 * 60 * 1000,
  targets: [
    {
      name: 'production-overlay',
      baseUrl: 'https://overlay.example',
      adminToken: process.env.ADMIN_TOKEN,
      probes: [
        {
          name: 'protomap',
          service: 'ls_protomap',
          query: { topic: 'tm_protomap' },
          maxOutputs: 50
        }
      ],
      maintenance: {
        startBASMSync: true,
        maintainUnproven: { thresholdBlocks: 144 },
        janitor: true
      }
    }
  ]
})

monitor.start()

Key concepts

  • OverlayExpress — Wraps Engine in Express with all routes auto-configured
  • Private key — Identifies the overlay node; used for signing advertisements and transactions
  • Advertising FQDN — Domain where this node is hosted; advertised in SHIP/SLAP for peer discovery
  • Admin token — Bearer token for protected endpoints (/admin/syncAdvertisements, /admin/startGASPSync)
  • Knex vs MongoDB — Knex for SQL (global application storage), MongoDB for per-service indices
  • Health endpoints — Follow Kubernetes liveness/readiness probe patterns
  • Browser preflights — Public CORS accepts additive well-formed request headers by default; set OVERLAY_CORS_ALLOWED_HEADERS only for a strict comma-separated browser header allowlist
  • JanitorService — Periodically validates SHIP/SLAP hosts; revokes failing entries
  • Provider callbacks — /arc-ingest accepts Arc/Arcade callback notifications, applies proofs, and evicts terminal invalid or double-spent transactions
  • Unproven maintenance — Proof refresh runs before eviction so mined transactions can recover before stale unproven rows are removed

When to use this

  • Deploying an overlay service to production
  • Running a node that serves multiple topics/lookup services
  • Need built-in health checks and monitoring
  • Want auto-generated web UI for service discovery
  • Scaling lookup services with MongoDB indices

When NOT to use this

  • For simple single-topic overlays without HTTP exposure
  • If you need custom HTTP framework (use @bsv/overlay directly)
  • For development without persistence (use @bsv/overlay in-memory)

Spec conformance

  • Implements BSV Overlay protocol with SHIP/SLAP peer discovery
  • Supports Graph Aware Sync Protocol (GASP) for historical sync
  • Health endpoints follow Kubernetes liveness/readiness probe patterns
  • Optional Arc and Arcade callback integration for proof-of-inclusion on mainnet
  • Chaintracks-compatible header and reorg handling for BRC-136 BASM

Common pitfalls

  1. Initialization order — configureKnex and configureMongo must complete before configureEngine()
  2. Admin token — Auto-generated if not provided; store securely for production
  3. Health check criticality — Mark as critical: true only for mandatory dependencies; failures block /health/ready
  4. GASP sync overhead — Disabling sync useful for dev but loses peer synchronization
  5. BanService persistence — Bans not persisted if MongoDB goes down; transient storage only
  6. Strict broadcast — Keep throwOnBroadcastFailure: true for production so provider outages do not create local-only overlay state.
  7. BASM dependencies — BASM should use a Chaintracks-compatible chain tracker; Arcade exposes this under /chaintracks/v2.
  8. Lifecycle ownership — Call await server.close() from the owning runtime so listeners, sync timers, reorg streaming, Knex, and MongoDB close together.

Related packages

  • @bsv/overlay — Core Engine and interfaces
  • @bsv/overlay-topics — Pre-built topic managers and lookup services
  • @bsv/overlay-discovery-services — SHIP/SLAP implementation
  • @bsv/gasp — Graph Aware Sync Protocol

Registering additional routers

registerRouter(path, factory) mounts an application router inside the server. The factory runs during start(), after the BRC-103 authentication middleware and before the admin routes and the 404 handler, so the router inherits CORS, body parsing, response size limits, and req.auth.identityKey. Unauthenticated requests arrive with req.auth.identityKey equal to 'unknown'. Call it before start().

ts
server.registerRouter('/', ({ engine, wallet }) => {
  if (wallet === undefined) throw new Error('A server wallet is required')
  const router = express.Router()
  router.get('/status', (_req, res) => res.json({ ok: true }))
  return router
})

The wallet in the context is the BRC-103 authentication wallet. It is built without a storage provider, so it signs and verifies but cannot create or internalize actions: createAction and internalizeAction throw. A router that takes payment, such as a BRC-178 host from @bsv/eqc, must build its own storage-backed wallet from the same root key as the server, so that its identity equals the BRC-103 session key and the SLAP-advertised key.

Registered routers inherit the response size limit (MAX_RESPONSE_BYTES: 4 MiB on the small profile, 8 MiB on standard). A larger JSON body is replaced by a 413 after the handler ran, so a router that is paid before it answers must bound its own responses below that limit.

Reference

  • API reference (TypeDoc)
  • Source on GitHub
  • npm

Optional authenticated proposals

configureProposals before start or the separate @bsv/overlay-express/proposals router composes the durable proposal service, service-owned disclosure validator and shared journal/native-enqueue gate. This entry requires SDK 3.3.0 and auth middleware 2.3; legacy root peer floors and routes remain unchanged. A current channel read differs from recovery of a retained publication ACK. Both require current authorization and original contract bounds after response signing. One sanitized replacement error may be signed, with independently checked control permission before native enqueue.

The host shares authentication and handshake ownership with lookup/root companions, keeps physical service work counted through settlement, clamps byte limits and inherits host CORS policy unless explicitly overridden. Storage, capability publication, verified recovery, expiry and admission workers remain host-owned. See the proposal guide for composition and recovery contracts.