Registry / web-framework / server-base

server-base

JSON →
library7.1.32jsnpmunverified

server-base is a foundational package designed for quickly setting up HTTP microservices or simple web servers. Currently at version 7.1.32, it provides core functionalities such as declarative request routing, middleware integration, and automatic `.env` file loading for configuration management. It leverages `server-base-router` for its routing engine and integrates structured logging capabilities via `server-base-log`, which itself builds upon `pino` for high-performance logging. Additionally, it uses `fast-json-stringify` for optimized JSON serialization. While the README doesn't specify a precise release cadence, its active development and frequent version updates suggest ongoing maintenance. Its key differentiator lies in its opinionated, modular approach to server development, focusing on simplicity, performance, and testability for small to medium-sized services, abstracting away common boilerplate found in more comprehensive frameworks.

npm install server-base
INSTALL
IMPORT
SIG · SERVER-BASE
S
server-base
web-frameworkjavascriptv7.1.32
Install
Import
Disk
Pass rate
0/ 6
Env Coverage0 / 6
glibc
1822
musl
1822
Install & Compatibility
Where this runs
tested against v? · npm install
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
musl
node 18226 runs
build_error
glibc
node 18226 runs
build_error
Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

service
const service = require('server-base')
import service from 'server-base'
server-base primarily uses CommonJS syntax. Direct ES module `import` might not work without specific Node.js configuration or a build step, leading to 'require is not defined' errors in ESM environments.
service
import service from 'server-base'
import { service } from 'server-base'
If using an environment configured for ESM (e.g., 'type': 'module' in package.json), the default export is intended. Using named imports like `{ service }` will likely result in 'service is not a function' or 'undefined' errors.

Initializes a `server-base` instance, setting up global middleware in the `@setup` hook and defining two API endpoints: a `/graphql` path with GET and async POST handlers (demonstrating JSON parsing), and a `/health` endpoint.

const service = require('server-base'); service({ '@setup': (ctx, router) => { // Example middleware: a simple pass-through. ctx.use() expects an array of middleware. ctx.use([ (req, res, next) => { console.log(`Incoming request: ${req.method} ${req.url}`); next(); } ]); // Middleware can also be added directly to the router if server-base-router allows. }, '/graphql': { get (req, res) { res.setHeader('Content-Type', 'text/html'); res.end('<h1>GraphQL Playground (GET)</h1><p>Not implemented yet.</p>'); }, async post (req, res) { try { const query = await req.json(); // Parses JSON body from request // In a real app, process the GraphQL query here console.log('Received GraphQL query:', query); res.json({ data: { message: 'Query received!', query: query } }); // Sends JSON response } catch (error) { console.error('Error processing GraphQL POST:', error); res.statusCode = 400; res.json({ errors: [{ message: 'Invalid JSON or query.' }] }); } } }, '/health': { get (req, res) { res.json({ status: 'ok', uptime: process.uptime() }); } } }) .start(process.env.PORT ?? 5000) .then(() => console.log(`Server started on port ${process.env.PORT ?? 5000}`));
Debug
Known issues
gotchaThe documentation and examples primarily use CommonJS `require()`. When working in a Node.js project configured for ES modules (`"type": "module"` in `package.json`), using `require()` will result in 'require is not defined in ES module scope' errors. Ensure your project type matches the import style.
fix
For ESM projects, try `import service from 'server-base';` and ensure Node.js is configured to handle CJS modules in an ESM context (e.g., by using an ESM wrapper or a build tool). If direct import fails, consider transpilation or using a CommonJS project setup.
affects: >=1.0.0
gotchaThe automatic `.env` file loading is handled by an internal `dotenv` dependency. If your application already initializes `dotenv` or another configuration loader, conflicts or unexpected behavior might occur as `server-base` will attempt to load environment variables again, potentially overwriting or ignoring existing configurations.
fix
Avoid initializing `dotenv` manually if `server-base` is used, or ensure explicit order of operations if custom environment loading is critical. Test thoroughly to prevent unintended configuration overrides.
affects: >=1.0.0
gotchaMiddleware functions in the `@setup` hook are expected to be provided as an array to `ctx.use([])`. Passing a single function or an incorrectly structured array may lead to the middleware not being registered or runtime errors.
fix
Always pass an array of middleware functions to `ctx.use()`, even if it's just a single function (e.g., `ctx.use([myMiddleware])`).
affects: >=1.0.0
gotchaserver-base uses `pino` for logging through `server-base-log`. This means traditional `console.log` statements are not integrated into the structured logging output and may not appear correctly in production log aggregators. Developers should use the provided logger instance.
fix
Access the logger instance (if exposed via context or options) and use its methods (e.g., `ctx.log.info('message')`, `ctx.log.error('error')`) for all application logging to ensure consistency and proper structured output.
affects: >=1.0.0
Errors
Common errors & fixes
TypeError: service is not a function
Attempting to call `service()` when the imported `service` variable is undefined or not the expected function, often due to incorrect CommonJS vs. ES module import syntax or a broken export.
fix
Ensure you are using `const service = require('server-base')` for CommonJS projects or `import service from 'server-base'` if your environment correctly handles ES Modules and the package exports a default. Double-check `package.json` for `"type": "module"` if using ESM.
Error: listen EADDRINUSE: address already in use :::PORT_NUMBER
The port number specified for the server to start on is already occupied by another process on your system, preventing `server-base` from binding to it.
fix
Change the port number in your `.start()` call (e.g., `.start(3001)`) or ensure no other applications are using the desired port. On Linux/macOS, `lsof -i :PORT_NUMBER` can identify the process, and `kill -9 PID` can terminate it.
Upgrade
Version history
7.1.32latest on npm
Audit
Dependencies
dotenvrequiredAutomatic loading of .env files into process.env for configuration.
server-base-routerrequiredProvides the core routing logic for defining HTTP endpoints and their handlers.
server-base-logrequiredOffers structured logging capabilities, built on top of Pino.
pinorequiredThe underlying high-performance logger used by server-base-log.
fast-json-stringifyrequiredUsed for optimized and fast JSON serialization of responses.
Agent activity
16 hits · last 30 days
node
14
OpenAI (training)
2
Resources
server-base — npm install server-base · libregistry