logoEframix

Using Middleware

Learn how to use middleware in your Eframix application.

Using Multiple Middleware

import Eframix, { Handler } from "eframix";
const app = new Eframix();
// Logging middleware
const loggingMiddleware: Handler = (req, res, next) => {
console.log(`[${new Date().toISOString()}] ${req.method} ${req.url}`);
next();
};
// Authentication middleware
const authMiddleware: Handler = (req, res, next) => {
const apiKey = req.headers['x-api-key'];
if (apiKey === 'secret-key') {
next();
} else {
res.statusCode = 401;
res.end('Unauthorized');
}
};
// Use global middleware
app.use(loggingMiddleware);
// Use middleware for specific routes
app.get('/api/protected', authMiddleware, (req, res) => {
res.end('Protected route accessed');
});
app.get('/', (req, res) => {
res.end('Hello, Eframix!');
});
app.startServer(3000, () => {
console.log('Server running on http://localhost:3000');
});

This example demonstrates how to use multiple middleware functions, both globally and for specific routes.