API Reference

Complete list of all exports from SpaceNode.

All Exports

import {
  createApp,         // Factory — creates app with auto-discovery
  dir,               // Resolve paths from import.meta.url
  defineAuth,        // Define global auth verification logic
  defineGuard,       // Register a global custom named guard
  dto,               // Create a validation schema
  validate,          // Validate data manually
  registerAdapter,   // Register Zod/Joi/Yup adapter
  setBodyParser,     // Set a custom body parser globally
  createModule,      // Create a module definition programmatically
  HttpError,         // HTTP error class
  ValidationError,   // Validation error (extends HttpError, 400)
  ModuleError,       // Module configuration error
  Logger,            // Structured logger with levels and transports
  EventBus,          // Event bus class
  Router,            // Trie router class
  Container,         // DI container class
  ScopedContainer,   // Scoped DI container (per-request)
} from 'SpaceNode'

createApp(config?) → Promise<SuperApp>

Creates the application. See createApp() page for full config.

Config KeyDefault
modulesDir'./modules'
baseUrlundefined — set to import.meta.url on serverless platforms
staticundefined
spatrue
dbnull
debugfalse
timeout30000
keepAliveTimeout5000
shutdownTimeout5000
pipe[]
bodyLimit1048576 (1MB)
openapi{}
recursivefalse
wsOriginsnull
staticCacheMax500
staticCacheFileSize256 * 1024
logger{}
trustProxyfalse
watchfalse — org-only auto-restart on file changes

dir(importMetaUrl, ...paths) → string

const envPath = dir(import.meta.url, '.env')
const dataDir = dir(import.meta.url, 'data', 'seeds')

defineAuth(verifier)

verifier: async (token: string, request?: object) => user | null

Defines global auth verification. The verifier receives the Bearer token and optionally the full request object. Can be overridden per-app with app.setAuth().

defineGuard(name, factory)

factory: (param?) => (request, services) => result | throw

Registers a global custom guard. Can also be done per-app with app.addGuard().

dto(schema) → object

Creates a named DTO validation schema from an object of rule arrays.

validate(data, schema) → cleanedData

Validates data manually. Throws ValidationError on failure.

registerAdapter(name, fn)

fn: (schema, data) => { errors?, output? }

setBodyParser(parser)

Set a custom global body parser function. parser: async (req) => { body, files? }

createModule(definition) → object

Create a module definition object programmatically.

HttpError(status, message, details?)

Properties: status, message, details. Method: toJSON().

ValidationError(errors)

Extends HttpError (status 400). errors: [{ field, message }]

ModuleError(moduleName, message)

Thrown when module configuration is invalid (missing routes, bad exports, etc.).

import { ModuleError } from 'SpaceNode'

// Properties:
// err.moduleName  — name of the broken module
// err.message     — "[Module: auth] Missing routes"
// err.name        — "ModuleError"

Logger(options?)

Structured logger with levels (error, warn, info, debug) and custom transport support.

const log = new Logger({ level: 'debug' })
log.info('Server started', { port: 3000 })

Logger.child(prefix)

Creates a child logger that prepends a prefix to all messages. Useful for per-module or per-request logging:

const log = new Logger({ level: 'info' })
const authLog = log.child('auth')

authLog.info('User logged in')
// Output: [2026-03-05T12:00:00.000Z] INFO  [auth] User logged in

authLog.error('Token expired', { userId: 42 })
// Output: [2026-03-05T12:00:00.000Z] ERROR [auth] Token expired {"userId":42}

The child inherits the parent's log level and timestamps setting. You can chain children: log.child('http').child('auth').

EventBus

Methods: on, once, emit, off, clear, listEvents, destroy

Router

Trie-based router. Methods: add, find, use, listRoutes

router.use(fn)

Adds a global middleware function that runs on every matched route, before the pipe pipeline:

app.router.use((request, services) => {
  request.startTime = Date.now()
})

Middleware added via use() runs before global pipes, module pipes, and route pipes. Multiple calls stack in order.

Container

DI container with lifecycle management. Methods: register, registerAll, singleton, transient, scoped, resolve, getAll, has, list, createScope, unregister, clear

ScopedContainer

Scoped child container (created via container.createScope()). Methods: resolve, getAll, has, list

SuperApp Properties

PropertyTypeDescription
app.eventsEventBusEventBus instance — use app.events.on(), .emit(), etc.
app.containerContainerDI Container instance — access registered services directly
app.routerRouterTrie router instance — direct access to route table
app.configobjectMerged configuration object passed to createApp()
app.dbanyDatabase reference (set via config or app.setDb())
app.debugbooleanWhether debug mode is enabled

SuperApp Instance Methods

MethodDescription
listen(port, cb?)Start HTTP server
close(cb?)Graceful shutdown (calls module onDestroy hooks, cleans up WebSockets, EventBus)
setDb(db)Set database reference
onError(fn)Global error handler
info()Returns app introspection object (see below)
setRoute(method, path, handler, pipes?)Imperative route registration
inject(opts)Simulate HTTP request for testing
ws(path, handler)Register WebSocket handler
setAuth(verifier)Set per-app auth verifier (token, request) => user | null (overrides global defineAuth)
addGuard(name, factory)Register per-app custom guard
setRateLimitStore(store)Plug custom rate limit store (e.g. Redis)
setBodyParser(parser)Set per-app custom body parser
addModule(definition)Add a module programmatically after app creation
handle(req, res)Raw request handler (for serverless / custom HTTP servers)

app.info() Return Value

app.info()
// Returns:
// {
//   modules:  ['auth', 'users', 'products'],    // module names
//   routes:   [{ method: 'GET', path: '/users' }, ...], // all registered routes
//   services: ['authService', 'userService', ...],      // DI service names
//   events:   ['order:created', 'user:registered', ...] // registered events
// }

Built-in Pipes

PipeDescription
authBearer token auth (requires defineAuth() or app.setAuth())
role:ROLERole check (requires auth first)
rateLimit:NPer-IP sliding-window rate limiter (N req/min)
cors / cors:ORIGINCORS headers + preflight
loggerRequest logging with timing
compress / compress:ENCODINGGzip/Brotli/Deflate compression
security / security:strictSecurity headers (HSTS, CSP, X-Frame-Options)
dto:NAMEBody validation against named DTO