SpaceNode
Complete list of all exports from SpaceNode.
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'
Creates the application. See createApp() page for full config.
| Config Key | Default |
|---|---|
modulesDir | './modules' |
baseUrl | undefined — set to import.meta.url on serverless platforms |
static | undefined |
spa | true |
db | null |
debug | false |
timeout | 30000 |
keepAliveTimeout | 5000 |
shutdownTimeout | 5000 |
pipe | [] |
bodyLimit | 1048576 (1MB) |
openapi | {} |
recursive | false |
wsOrigins | null |
staticCacheMax | 500 |
staticCacheFileSize | 256 * 1024 |
logger | {} |
trustProxy | false |
watch | false — org-only auto-restart on file changes |
const envPath = dir(import.meta.url, '.env')
const dataDir = dir(import.meta.url, 'data', 'seeds')
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().
factory: (param?) => (request, services) => result | throw
Registers a global custom guard. Can also be done per-app with app.addGuard().
Creates a named DTO validation schema from an object of rule arrays.
Validates data manually. Throws ValidationError on failure.
fn: (schema, data) => { errors?, output? }
Set a custom global body parser function. parser: async (req) => { body, files? }
Create a module definition object programmatically.
Properties: status, message, details. Method: toJSON().
Extends HttpError (status 400). errors: [{ field, 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"
Structured logger with levels (error, warn, info, debug) and custom transport support.
const log = new Logger({ level: 'debug' })
log.info('Server started', { port: 3000 })
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').
Methods: on, once, emit, off, clear, listEvents, destroy
Trie-based router. Methods: add, find, use, listRoutes
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.
DI container with lifecycle management. Methods: register, registerAll, singleton, transient, scoped, resolve, getAll, has, list, createScope, unregister, clear
Scoped child container (created via container.createScope()). Methods: resolve, getAll, has, list
| Property | Type | Description |
|---|---|---|
app.events | EventBus | EventBus instance — use app.events.on(), .emit(), etc. |
app.container | Container | DI Container instance — access registered services directly |
app.router | Router | Trie router instance — direct access to route table |
app.config | object | Merged configuration object passed to createApp() |
app.db | any | Database reference (set via config or app.setDb()) |
app.debug | boolean | Whether debug mode is enabled |
| Method | Description |
|---|---|
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()
// 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
// }
| Pipe | Description |
|---|---|
auth | Bearer token auth (requires defineAuth() or app.setAuth()) |
role:ROLE | Role check (requires auth first) |
rateLimit:N | Per-IP sliding-window rate limiter (N req/min) |
cors / cors:ORIGIN | CORS headers + preflight |
logger | Request logging with timing |
compress / compress:ENCODING | Gzip/Brotli/Deflate compression |
security / security:strict | Security headers (HSTS, CSP, X-Frame-Options) |
dto:NAME | Body validation against named DTO |