New Research: Supply Chain Attack on Axios Pulls Malicious Dependency from npm.Details →
Socket
Book a DemoSign in
Socket

nutraj

Package Overview
Dependencies
Maintainers
1
Versions
1
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

nutraj

A lightweight Express‑like framework with multi‑domain support, middleware, dynamic routing, static file serving, and built‑in utilities such as cookie parsing, logging, CORS, sessions, and optional API statistics.

latest
Source
npmnpm
Version
1.0.0
Version published
Maintainers
1
Created
Source

🍂 Nutraj

npm version npm downloads License: MIT

Nutraj is a lightweight, Express‑inspired framework for Node.js that empowers you to build robust APIs and serve static websites effortlessly. With built‑in multi‑domain support, optional API performance tracking, and an extensive middleware suite, Nutraj goes a step further—offering pro features that outshine Express.

Why Nutraj?
Nutraj not only replicates Express's simplicity but also extends it with advanced features like multi-domain hosting, dynamic API statistics, and multiple static folder support. It's designed to be modular, fast, and easy to extend, making it a perfect choice for modern Node.js applications.

✨ Features

  • Express-like API:
    Familiar routing methods (app.get, app.post, etc.) and middleware chaining for rapid development.

  • Multi-Domain Handling (Pro Feature):
    Easily host multiple websites on a single server by delegating requests based on the Host header.
    Express does not natively support multi-domain routing.

  • Dynamic Routing:
    Parameterized routes (e.g., /user/:id) with automatic extraction to req.params.

  • Built-in Middlewares:

    • Logger: Detailed request logging with timestamps, HTTP method, URL, status code, and response time.
    • Cookie Parser: Automatically parses cookies into req.cookies.
    • Body Parser: Parses JSON, URL-encoded, and multipart/form-data (file uploads via formidable).
    • Session Management: Simple in-memory session support with automatic cookie handling.
    • User-Agent Parsing: Direct access to client user-agent details via req.useragent.
    • CORS: Easily enable Cross-Origin Resource Sharing with customizable options.
    • Static File Serving: Seamlessly serve assets from multiple directories.
  • Response Enhancements:
    Built-in methods like res.send(), res.json(), res.sendFile(), and res.redirect() simplify response handling.

  • Optional API Statistics (Pro Feature):
    Track endpoint performance—hits, total response time, and average response time—with a built‑in /__stats endpoint.
    This powerful feature is disabled by default and can be enabled via middleware (app.use(app.stats)).

  • Extensible & Customizable:
    Create custom middleware or error handlers effortlessly. Nutraj’s architecture allows you to plug in additional functionality as your application grows.

📦 Installation

Install Nutraj via npm:

npm install nutraj

🚀 Quick Start

Create a file named server.js:

const path = require('path');
const Nutraj = require('nutraj');
const app = Nutraj();

// Global middleware
app.use(app.logger);
app.use(app.cookieParser);
app.use(app.useragent);
app.use(app.bodyParser);
app.use(app.session);
// Enable CORS with default settings
app.use(app.cors());

// OPTIONAL: Enable API statistics (disabled by default)
// app.use(app.stats);

// Serve static files from multiple directories
app.use(app.static('public'));
app.use(app.static('assets'));

// Basic route with res.send()
app.get('/', (req, res) => {
  res.send('Welcome to Nutraj – A Lightweight Express Alternative with Pro Features!');
});

// Dynamic route using route parameters
app.get('/hello/:name', (req, res) => {
  res.send(`Hello, ${req.params.name}! Your user-agent is: ${req.useragent}`);
});

// POST route with full body parsing (JSON, URL-encoded, file uploads)
app.post('/submit', (req, res) => {
  res.json({
    message: 'Data received successfully!',
    body: req.body,
    files: req.files || {},
    query: req.query
  });
});

// Route for redirection
app.get('/redirect', (req, res) => {
  res.redirect('/');
});

// Serve a file (ensure "./public/sample.txt" exists)
app.get('/file', (req, res) => {
  res.sendFile(path.join(__dirname, 'public', 'sample.txt'));
});

// Built-in API statistics endpoint (only active if stats middleware is enabled)
app.get('/__stats', (req, res) => {
  res.json({ message: 'Enable API statistics middleware (app.stats) to see route stats.' });
});

// Multi-domain example:
// Create a sub-app for the blog domain.
const blogApp = Nutraj();
blogApp.get('/', (req, res) => {
  res.send('Welcome to the Blog!');
});
blogApp.get('/post/:slug', (req, res) => {
  res.send(`Displaying blog post: ${req.params.slug}`);
});
// Register the sub-app for the domain "blog.example.com"
app.domain('blog.example.com', blogApp);

// Start the server
app.listen(3000, () => {
  console.log('Nutraj server is running on port 3000');
});

Run your server with:

node server.js

🛠 Detailed API & Middleware

Core Routing

Nutraj supports all standard HTTP methods and dynamic routing:

// Define a GET route
app.get('/users', (req, res) => {
  res.send('User list');
});

// Define a POST route
app.post('/users', (req, res) => {
  res.send('User created');
});

// Define a dynamic route with parameters
app.get('/users/:id', (req, res) => {
  // Access route parameter via req.params.id
  res.send(`User ID: ${req.params.id}`);
});

Response Enhancements

Nutraj extends the response object with these helper methods:

  • res.send(body):
    Sends a string or object as a response. Automatically sets appropriate headers.
  • res.json(data):
    Sends JSON data with correct Content-Type headers.
  • res.sendFile(filePath):
    Streams a file directly to the client, handling errors gracefully.
  • res.redirect(url, [statusCode]):
    Redirects the client to a specified URL (default status code is 302).

Built-in Middlewares

Nutraj comes with an extensive suite of middleware functions to boost productivity:

Logger

Logs each request with detailed information including method, URL, status code, and response time.

app.use(app.logger);

Automatically parses cookies from incoming requests and populates req.cookies.

app.use(app.cookieParser);

Body Parser

Supports parsing JSON, URL-encoded, and multipart/form-data requests.

app.use(app.bodyParser);

Session Management

Handles simple in-memory sessions. A session cookie (nutraj_session) is set automatically if not present.

app.use(app.session);

User-Agent Parser

Provides easy access to the client’s user-agent via req.useragent.

app.use(app.useragent);

CORS Middleware

Enables Cross-Origin Resource Sharing with flexible configuration options.

app.use(app.cors());
// Or configure with options:
app.use(app.cors({ origin: 'https://example.com', methods: 'GET,POST' }));

Static File Serving

Serve static files from one or more directories. Nutraj processes multiple static middlewares in the order they are added.

app.use(app.static('public'));
app.use(app.static('assets'));

API Statistics (Optional)

Enable detailed per-route performance tracking by using:

app.use(app.stats);

When activated, Nutraj tracks:

  • Hits: Total calls per endpoint.
  • Total Response Time: Cumulative processing time.
  • Average Response Time: Average processing time per request.

Access statistics at the /__stats endpoint.

Multi-Domain Handling

Nutraj excels in multi-domain support. Create sub-applications for different domains and delegate requests based on the Host header.

// Create a sub-app for the blog domain
const blogApp = Nutraj();
blogApp.get('/', (req, res) => { res.send('Welcome to the Blog!'); });
blogApp.get('/post/:slug', (req, res) => { res.send(`Post: ${req.params.slug}`); });

// Register the sub-app for "blog.example.com"
app.domain('blog.example.com', blogApp);

Requests with the host blog.example.com are automatically routed to blogApp, giving you native multi-domain support without additional configuration.

💡 Pro Tips & Best Practices

  • Middleware Order:
    Register global middleware (e.g., logging, body parsing) before your routes for best performance.
  • Multiple Static Folders:
    Chain multiple app.static() calls if your project contains assets spread across different directories.
  • Custom Middleware:
    Extend Nutraj by writing your own middleware functions. For error handling, define middleware with four parameters:
    app.use((err, req, res, next) => {
      res.statusCode = 500;
      res.send(`Custom Error: ${err.message}`);
    });
    
  • Monitor Performance:
    Use the API statistics middleware during development to gain insights and optimize your endpoints.
  • Multi-Domain Setup:
    Ensure your DNS and server configurations forward the correct host headers to your Nutraj server.

🚀 Extra Advantages Over Express

Nutraj not only replicates Express’s simplicity but also offers additional features:

  • Built-in Multi-Domain Routing:
    Host several domains from a single server without extra configuration.
  • Optional API Performance Tracking:
    Instantly monitor endpoint performance and usage with the API statistics middleware.
  • Multiple Static Folders:
    Serve files from various directories seamlessly.
  • All-in-One Package:
    Integrated cookie parsing, session management, user-agent detection, and CORS support—all bundled in one lightweight framework.

These pro features make Nutraj an attractive choice for modern, performance-oriented Node.js applications.

🛡 License

MIT

👨‍💼 Author

Made with ❤️ by Vaibhav Panday

Contributions, issues, and pull requests are welcome! If you find Nutraj useful, please consider buying me a coffee.

Enjoy building with Nutraj!

Keywords

express

FAQs

Package last updated on 26 Mar 2025

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts