-
Notifications
You must be signed in to change notification settings - Fork 0
Usage
This guide explains how to use Simple API Router to streamline your Express API development.
Once installed, Simple API Router automatically loads all routes from the api/
directory into your Express app.
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.
Your API files should be placed inside an api/
folder. Each file defines a set of routes.
my-project/
βββ api/
β βββ router.js
β βββ user.js
β βββ product.js
βββ package.json
βββ server.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
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.
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');
});
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.
-
Learn how to [generate API clients](Generating-API-Clients).
-
Contribute to the project in the [Contributing](Contributing) section.
π‘ Need help? Open an [issue](../issues) or join the [discussions](../discussions).