node-rest-server
A configuration-driven Node.js REST server with Express middleware support and built-in response handling.
The package ships as an ES module bundle with TypeScript declarations.
Features
- Configure REST endpoints with minimal boilerplate
- Supports all standard HTTP methods and async controllers
- Built-in response types:
payload,error,file, andhtml - Global request filter with async support
- Per-route Express-compatible middleware support
- Configurable CORS, headers, delay, and HTTPS options
- Graceful and forced server shutdown support
- Fully typed TypeScript exports
Installation
Install from npm:
npm install --save node-rest-serverInstall from GitHub Packages:
npm install @nishant-labs/node-rest-serverImporting
ES Modules (recommended)
import NodeRestServer from 'node-rest-server';
import { RouteConfiguration, ServerConfiguration } from 'node-rest-server';CommonJS
const NodeRestServer = require('node-rest-server');
const { RouteConfiguration, ServerConfiguration } = require('node-rest-server');Quick Start
import NodeRestServer from 'node-rest-server';
const routeConfig = {
'/api1': {
method: 'GET',
status: 200,
headers: { 'x-data': 'value' },
controller: () => ({ payload: 'Data' }),
},
};
const serverConfig = {
port: 8080,
};
const server = NodeRestServer(routeConfig, serverConfig);Server Events
The returned server instance supports Node HTTP event listeners:
listeningcloseconnectionerrorrequestclientError
Example:
server.addListener('listening', () => console.log('Server started'));
server.addListener('close', () => console.log('Server shutdown complete'));Shutdown
The server exposes a close method that returns a Promise<Error | undefined>:
await server.close();
await server.close(true);close()performs graceful shutdown and waits for active requests to finishclose(true)forces immediate shutdown and closes open connections
Route Configuration
A route configuration maps a path to either a single route item or an array of route items for the same path.
Route item options
| Name | Type | Default | Description |
|---|---|---|---|
method |
GET | POST | PUT | DELETE | PATCH | HEAD | OPTIONS | ALL |
GET |
HTTP method for the route |
status |
number |
200 |
HTTP response status code |
headers |
Record<string, string> |
- | Response headers for this route |
middlewares |
Array<ExpressMiddlewareFunc> |
- | Express-compatible middleware for this route |
controller |
Function | Object | Promise |
- | Controller response or controller function |
Controller signature
A controller receives:
requestDataurlbodypathParamsqueryParamsheadersmethodrawRequest(original Express request object)filter(data returned from global filter)
controllerOptionsgetDatabaseConnection
Controllers can return:
- an object with
status,headers, andpayload - an object with
error,file, orhtml - plain JSON-serializable data
- a
Promiseresolving to any of the above
Example:
return {
status: 201,
headers: { 'x-created': 'true' },
payload: { message: 'Created' },
};Example route configuration
const routeConfig = {
'/endpoint1': {
method: 'GET',
status: 200,
headers: { 'x-data': 'value' },
controller: () => ({ payload: 'Data' }),
},
'/endpoint2': {
method: 'POST',
controller: async (requestData, { getDatabaseConnection }) => {
const connection = await getDatabaseConnection?.(requestData);
return { status: 200, payload: { data: 'Data', connection } };
},
},
'/endpoint3': [
{
method: 'POST',
controller: async (requestData) => {
const { rawRequest } = requestData;
return { status: 200, payload: { data: 'Async data', path: rawRequest.path } };
},
},
{
method: 'GET',
controller: (requestData) => ({ status: 200, payload: { filter: requestData.filter } }),
},
],
};Server Configuration
| Name | Type | Default | Description |
|---|---|---|---|
basePath |
string |
- | Common prefix for all routes |
port |
number |
8000 |
Port to listen on |
delay |
number |
0 |
Delay response by seconds |
logger |
boolean |
LoggerConfiguration|true |
Enable logging or pass logger settings such as level and output file |
getDatabaseConnection |
function |
- | Async helper available in controllers |
filter |
function |
- | Global request filter, supports promises |
cors |
CorsOptions |
- | CORS configuration for the cors package |
headers |
Record<string, string> |
function |
Global response headers or function returning headers |
middlewares |
Array<ExpressMiddlewareFunc> |
- | App-level Express middleware |
https |
https.ServerOptions |
- | Enable HTTPS server with Node options |
Example server configuration
const serverConfig = {
basePath: '/base/api',
port: 8080,
delay: 2,
logger: {
enable: true,
level: 'info',
file: './logs/server.log',
},
getDatabaseConnection: async (requestData) => {
return Promise.resolve('db connection');
},
filter: async (requestData) => {
return { user: 'test-user', requestTime: Date.now() };
},
cors: {
origin: '*',
},
headers: (requestData) => ({
'x-data': 'my header',
'x-request-method': requestData.method,
}),
middlewares: [
(req, res, next) => {
console.log('route middleware');
next();
},
],
};Advanced Response Types
Controller results may include:
payload: sends JSON responseerror: sends{ error }JSON responsefile: sends a file using ExpresssendFilehtml: sends raw HTML using Expresssend
Examples
See the examples directory for working samples.
