Full API Specification
Complete technical reference for the @harshitclub/nodeframe package.
Package Exports
import NodeFrame, {
parseJsonBody,
logger,
rateLimiter
} from "@harshitclub/nodeframe";| Export | Type | Description |
|---|---|---|
default | typeof NodeFrame | The main NodeFrame application class. |
parseJsonBody | MiddlewareFunction | Middleware that parses incoming JSON request bodies. |
logger | () => MiddlewareFunction | Factory function returning a request logging middleware. |
rateLimiter | (options?: RateLimiterOptions) => MiddlewareFunction | Factory function returning an in-memory IP rate-limiting middleware. |
NodeFrame Class
constructor()
Creates a new NodeFrame application instance.
const app = new NodeFrame();Internal Properties
app.routes: Object map of registered routes grouped by HTTP method ({ GET: {}, POST: {}, PUT: {}, PATCH: {}, DELETE: {} }).app.middlewares: Array of registered normal middleware functions(req, res, next).app.errorMiddlewares: Array of registered error-handling middleware functions(error, req, res, next).
Route Methods
app.get(path, handler)
Registers a route handler for GET requests.
path(string): Static route (e.g.,"/users") or dynamic route pattern (e.g.,"/users/:id").handler((req: EnhancedRequest, res: EnhancedResponse) => void): The route handler function.
app.post(path, handler)
Registers a route handler for POST requests.
app.put(path, handler)
Registers a route handler for PUT requests.
app.patch(path, handler)
Registers a route handler for PATCH requests.
app.delete(path, handler)
Registers a route handler for DELETE requests.
app.registerRoute(method, path, handler)
Low-level route registration method used internally by the HTTP helper methods.
method(string): HTTP method (e.g.,'GET','POST').path(string): Route path pattern.handler(Function): Route handler callback.
Middleware Methods
app.use(handler)
Registers a middleware function into the application pipeline.
- If
handler.length === 4, it is stored inapp.errorMiddlewaresas error-handling middleware. - Otherwise, it is stored in
app.middlewaresas normal middleware.
// Normal Middleware
app.use((req, res, next) => {
next();
});
// Error Middleware
app.use((error, req, res, next) => {
res.status(500).json({ error: error.message });
});Server Lifecycle
app.listen(port, callback?)
Creates and starts the underlying Node.js http.Server.
port(number): Port number to bind and listen on.callback(Function, optional): Callback invoked once the server starts listening.- Returns:
http.Server— The native Node.js HTTP server instance.
const server = app.listen(3000, () => {
console.log("Server listening on port 3000");
});Internal Routing Helpers
app.matchRoute(req)
Matches the request against registered dynamic route patterns for req.method.
- Parameters:
req(IncomingMessage) - Returns:
{ handler: Function, params: Record<string, string> } | null
app.handleRoute(req, res, next)
Executes dynamic route matching followed by static route lookup. If no route matches, sends a 404 Not Found response. Catches synchronous errors and calls next(error).
Enhanced Request Object
NodeFrame extends the native Node.js http.IncomingMessage instance with the following properties:
req.query
- Type:
Record<string, string> - Description: Key-value pairs parsed from the URL search query using
URLSearchParams.
req.params
- Type:
Record<string, string> - Description: Key-value pairs extracted from dynamic route segments matching
:paramName.
req.body
- Type:
any - Description: Parsed JSON payload populated when using the
parseJsonBodymiddleware.
Enhanced Response Object
NodeFrame extends the native Node.js http.ServerResponse instance with chainable helper methods:
res.status(code)
code(number): HTTP status code.- Returns:
res(for method chaining).
res.json(data)
data(any): Object or value to be serialized as JSON. Sets headerContent-Type: application/jsonand callsres.end().- Returns:
res(for method chaining).
res.send(data)
data(string | Buffer | Uint8Array): Raw data payload transmitted viares.end(data).- Returns:
res(for method chaining).
res.cookie(name, value, options?)
name(string): Cookie identifier.value(string): Cookie value.options(CookieOptions, optional):httpOnly(boolean, defaulttrue): Appends; HttpOnly.secure(boolean, defaulttrue): Appends; Secure.maxAge(number, default86400000): Lifetime in milliseconds (converted toMax-Ageseconds).path(string): URL path scope for the cookie.sameSite(string): SameSite attribute ('Strict','Lax','None').domain(string): Host domain scope.
- Returns:
res(for method chaining).
Built-in Utilities
parseJsonBody(req, res, next)
- Type: Middleware function.
- Streams and parses request bodies for requests with
Content-Type: application/json. - Attaches the parsed object to
req.body. - Responds with
400 Bad Request({ success: false, message: "Invalid JSON" }) on malformed JSON.
logger()
- Type:
() => (req, res, next) => void - Returns middleware that records request start time and logs format
${method} ${url} ${statusCode} ${duration}msupon responsefinish.
rateLimiter(options?)
- Type:
(options?: RateLimiterOptions) => (req, res, next) => void options.windowMs(number, default:60000): Window size in milliseconds.options.maxRequests(number, default:5): Maximum requests allowed per IP address in each window.- Responds with
429 Too Many Requests({ success: false, message: "Too many requests" }) when limit is exceeded.