serverApp
Official sources are open to Staxis GitLab group members: how to join and view the code.
Repository:
serverApp development
Versions:
tags
and releases
Description
serverApp is the provider layer that prepares the shared HTTP application used by the rest of the stack. Its label and typology are both serverApp. The standard Staxis delivery uses native Node.js HTTP, without a third-party web framework. Express, Fastify, and Koa are optional compatibility paths for developers extending their own applications.
Read before flight
Native Node.js is the standard delivery. Validate the selected runtime and shutdown behaviour before exposing the application to traffic. The current release has these specific limitations:
-
β Native fallback: safeEnd can send a body describing 404 or 500 while retaining HTTP status 200. Set explicit response statuses and provide a final middleware for unmatched requests. The routing root fallback explicitly sets 404.
-
β Framework adapters: response-completion wrappers call chainEnd, which is currently defined only in native mode. This can raise an error on Express, Fastify, or Koa even with chainlog disabled. The supplied framework paths need correction and validation before deployment.
-
β Listener ownership: detach replaces the published application surface without closing an existing listener or revoking retained references. Let httpListener manage its listener, or explicitly stop one started by your own pack.
-
β Dependencies: allowBareDeps is a global Guardian setting. Optional frameworks and their dependencies become part of the runtime you must review. Keep the per-pack dependency rules and consumer permits deliberate.
What It Does
Consumers register named middleware with using(label, handler), or build a routing handler with routing(routes, options). serverApp.kind identifies the selected runtime. In native mode, the object also exposes listen and stop.
Preparing the application and starting the network listener are separate responsibilities. In a regular stack, serverApp prepares the application, consumer packs register their middleware, and httpListener starts the server and manages its connections. Avoid starting a second listener manually when httpListener already owns that job.
Files Map
| File | Purpose |
|---|---|
| manifest.json | Declares the layer identity and permitted consumers |
| configs.js | Provides dependency rules and server defaults |
| main.js | Detects the runtime, creates the application, and publishes its bundle |
| adapt.native.js | Implements native HTTP and the shared using and routing surface |
| adapt.express.js, adapt.fastify.js, adapt.koa.js | Prepare the corresponding optional framework adapters |
| README.md | Pack reference and basic using example |
Requirements and Installation
Native mode requires no external npm dependency and no other pack. Install serverApp through the Manager:
manager -> install -> serverApp
Put serverApp before its consumer packs in the stack. Consumers can declare "require": ["serverApp"]. Configure KEY:SERVERAPP and the project's Vault keys, review integrity records, and keep each caller's label in the provider's manifest permits list. Add the requesting pack's label to that list while preserving the other permitted consumers.
Configuration
In the project's config.js, these flags belong to config.serveropt. Merge the following serveropt branch into the exported config object:
// config.js -> config (merge into the exported object)
serveropt: {
safeEnd: true,
proxySets: false,
proxyLimiter: false,
chainlog: false
}
- safeEnd enables the native fallback response when the middleware chain ends or reports an error. If you disable it, provide the completion and error handling yourself.
- proxySets and proxyLimiter configure experimental proxy behaviour in framework adapters. Leave them disabled unless your deployment deliberately trusts a known proxy setup. The native adapter does not interpret forwarded client addresses through these settings.
- chainlog enables the middleware trace report in native mode. This is a server-specific switch, separate from engineopt.audit.logDebug and logDeeply.
The pack also supplies engineopt.guard.allowBareDeps=true and an allowedDeps entry for serverApp covering express, fastify, koa, and native. allowBareDeps is a global Guardian option; per-pack dependency rules still apply. Preserve the other project rules when merging configuration. No npm package named native is required: native mode imports node:http.
Request Access
The examples use somelayer as the requesting pack's manifest.label. Replace it with your own pack label and add that label to serverApp's manifest permits before requesting access. Both arguments to engine.vault.requireAccess are pack labels from manifest.json: first the requesting pack, then the provider. In contrast, layers.require selects the provider's runtime typology, its slot in the stack. The official serverApp pack uses serverApp for both its label and its typology, so the two names happen to match here. Request the instance with false, then read its assets.
const tokenAccess = engine.vault.requireAccess(
'somelayer', // Requester's manifest.label: replace with your own pack label
'serverApp' // Provider's manifest.label
)
if (typeof tokenAccess !== 'string' || tokenAccess.startsWith('error:')) {
throw new Error('serverApp access denied')
}
const bundle = layers.require(
'serverApp', // Provider's manifest.typology: runtime slot
tokenAccess,
false
)
const serverApp = bundle?.assets
if (!serverApp || typeof serverApp.using !== 'function') {
throw new Error('serverApp is unavailable')
}
Register Middleware with using
using(label, handler) registers a handler with the Node-style signature (req, res, next). The label names the middleware for diagnostics; it is separate from the consumer's pack label. End the response when handling a request, or call next() to pass it onwards.
serverApp.using('hello-route', (req, res, next) => {
if (req.url !== '/hello') return next()
res.statusCode = 200
res.setHeader('Content-Type', 'text/plain; charset=utf-8')
res.end('hello')
})
Native middleware runs in registration order. The handler above matches /hello exactly; /hello?name=test is a different req.url. Use routing when matching the pathname separately from query parameters. Native mode catches synchronous exceptions and rejected handler promises.
Register Routes
routing returns a middleware function; pass that function to using to register it. Each route has a role RegExp, a handler, and optional methods. Options include root and methodsDefault. Route handlers receive (req, res, next, matched, pathname).
serverApp.using('api-routes', serverApp.routing([
{
role: /^\/api\/hello$/,
methods: ['GET'],
handler: (req, res, next, matched, pathname) => {
res.statusCode = 200
res.setHeader('Content-Type', 'text/plain; charset=utf-8')
res.end('hello from ' + pathname)
}
}
], {
root: '/api'
}))
root limits the namespace handled by this middleware; it does not remove the prefix before matching role. Requests outside /api continue to the next middleware. Unmatched requests inside that root receive a 404, including requests with unsupported methods. Without root, unmatched requests continue through next(). Avoid stateful RegExp flags such as g or y for route patterns.
Start and Stop in Native Mode
For a minimal native application without httpListener, the README's direct-listen approach is available. Run this after registering handlers and keep one owner for the listener. The example binds only to the local host.
if (serverApp.kind === 'native') {
const listener = serverApp.listen(3000, '127.0.0.1')
listener.on('error', error => {
logs('error', 'somelayer', '', error.message)
})
}
Native listen returns a Node.js HTTP server. Its built-in defaults are port 3000 and host 0.0.0.0 when omitted. Native stop stops accepting connections and destroys remaining tracked sockets after timeoutMs, which defaults to 3000 milliseconds. Await it during your own shutdown:
if (serverApp.kind === 'native') {
await serverApp.stop({ timeoutMs: 3000 })
}
Extend with Express, Fastify, or Koa
Staxis supplies native Node.js as its standard HTTP path. Choosing a framework is a developer extension: you add the dependency, select compatible versions and middleware, and validate the resulting application. serverApp includes adapter code for these choices; it does not install those frameworks as a requirement of the native stack. Read the current release warnings before using those adapters.
Select One Framework
During attach, serverApp probes express, fastify, and koa through npm ls with depth=0. One detected package selects its adapter; none selects native. More than one detected framework produces an initialization error. There is no configuration switch that overrides this selection. The npm command must be available and able to inspect the project dependencies.
// Choose ONE framework for your project
npm install express
// Alternative
npm install fastify
// Alternative
npm install koa
Keep only your chosen framework among these direct dependencies, then restart the application. A failed dependency probe is treated as absence, so check serverApp.kind after startup rather than assuming the installed framework was selected. The published assets are the application instance created by that framework, extended with Staxis methods.
Shared Signature and Framework Boundaries
- Native and Express using handlers receive req, res, and next; Express registration delegates to app.use. Express also receives text and JSON body parsers from its adapter.
- Fastify using handlers run in onRequest with request.raw and reply.raw. The supplied next is a no-op: Fastify proceeds when the async hook completes. Framework-parsed bodies are not available at this early hook stage.
- Koa using handlers receive ctx.req and ctx.res, with next bridged to Koa's continuation. Await or return next() when forwarding an asynchronous request. For Koa's context and response semantics, use its own middleware API.
The common signature does not make the frameworks' request lifecycles identical. Keep portable handlers to the shared request and response operations, and use framework-specific APIs when your application depends on framework routing, plugins, context, or body parsing.
Use the Selected Framework's API
These examples extend the same serverApp obtained through the Vault above. Register routes before the listening layer starts. They illustrate each framework's own API; they do not create another application instance or another listener.
if (serverApp.kind === 'express') {
serverApp.get('/framework-hello', (req, res) => {
res.type('text/plain').send('hello from Express')
})
}
if (serverApp.kind === 'fastify') {
serverApp.get('/framework-hello', async (request, reply) => {
return reply.type('text/plain').send('hello from Fastify')
})
}
if (serverApp.kind === 'koa') {
serverApp.use(async (ctx, next) => {
if (ctx.method !== 'GET' || ctx.path !== '/framework-hello') {
return next()
}
ctx.status = 200
ctx.type = 'text/plain'
ctx.body = 'hello from Koa'
})
}
Refer to the selected framework's documentation for its API: Express, Fastify, and Koa. Framework plugins and any dependencies imported by your own pack need their own installation and applicable Guardian dependency rules.
Application Ownership
Direct access to the framework instance also grants its registration and lifecycle methods. Manifest permits authorize the consumer to obtain that instance; they do not constrain each route it can register or each method it can subsequently call. Keep ownership of startup, shutdown, user authorization, and proxy trust explicit in your application.
Documentation
This page is the HTML adaptation of the pack's README.md, with practical clarifications checked against the implementation. Complete Staxis onboarding to request GitLab access to the official sources.