Writing Middleware
Learn how to write custom middleware for your Eframix application.
What is Middleware?
Middleware is a function that has access to the request, response, and the next middleware function in the application's request-response cycle. It can perform various tasks such as:
- Executing code.
- Modifying the request and response objects.
- Ending the request-response cycle.
- Calling the next middleware function in the stack.
Middleware can be used for various purposes, including logging, authentication, error handling, and more.
Custom Logging Middleware
Below is an example of a simple logging middleware that logs the request method and URL along with the timestamp.
import Eframix, { Handler } from 'eframix';const app = new Eframix();// Logging middlewareconst loggingMiddleware: Handler = (req, res, next) => {console.log(`[${new Date().toISOString()}] ${req.method} ${req.url}`);next();};// Use global middlewareapp.use(loggingMiddleware);app.get('/', (req, res) => {res.end('Hello, Eframix!');});app.startServer(3000, () => {console.log('Server running on http://localhost:3000');});
This middleware logs the method and URL of every incoming request to the console.