Skip to content
NotNexx edited this page Feb 24, 2025 · 1 revision

πŸš€ Usage Guide

This guide explains how to use Simple API Router to streamline your Express API development.

1️⃣ Basic Usage

Once installed, Simple API Router automatically loads all routes from the api/ directory into your Express app.

Example:

const express = require('express');
const loadRoutes = require('@notnexx/n-sar');

const app = express();
const PORT = 3000;

app.use(express.json());
loadRoutes(app);

app.listen(PORT, () => {
    console.log(`Server running at http://localhost:${PORT}`);
});

This setup automatically detects all .js files inside the api/ directory and registers them as Express routes.


2️⃣ API Directory Structure

Your API files should be placed inside an api/ folder. Each file defines a set of routes.

Example Structure:

my-project/
β”œβ”€β”€ api/
β”‚   β”œβ”€β”€ router.js
β”‚   β”œβ”€β”€ user.js
β”‚   └── product.js
β”œβ”€β”€ package.json
└── server.js

Example API File: api/user.js

const express = require('express');
const router = express.Router();

router.get('/', (req, res) => {
    res.json({ message: 'User endpoint' });
});

router.post('/', (req, res) => {
    res.json({ message: 'User created' });
});

module.exports = router;

This will automatically create the following endpoints:

GET  /user
POST /user

3️⃣ Automatically Generating a Sample API Project

To quickly set up a new API project with a predefined structure, run:

npx n-sar create my-api-project

This generates a basic API project, installs dependencies, and prepares it for immediate use.


4️⃣ Middleware Support

You can use Express middleware as usual. For example, adding authentication:

const express = require('express');
const loadRoutes = require('@notnexx/n-sar');
const app = express();

app.use(express.json());

// Example: Add authentication middleware
app.use((req, res, next) => {
    console.log(`Request to ${req.path}`);
    next();
});

loadRoutes(app);

app.listen(3000, () => {
    console.log('Server running on port 3000');
});

5️⃣ Hot Reloading (Optional)

To automatically reload your API on changes, use nodemon:

npm install -g nodemon
nodemon server.js

Now, any changes to your API files will be detected without restarting the server manually.


πŸ“– Next Steps

πŸ’‘ Need help? Open an [issue](../issues) or join the [discussions](../discussions).