Middleware
Middleware functions are functions that have access to the request
object (req), the response object (res), and
the next middleware function in the application’s request-response
cycle.
Global Middleware
Global middleware runs for every request to the application.
app.use((req, res, next) => {
console.log(`[${new Date().toISOString()}] ${req.method} ${req.url}`);
next();
});
Path-Specific Middleware
You can mount middleware at a specific path. The middleware function is
executed when the base of the requested path matches path.
app.use('/admin', (req, res, next) => {
// Only runs for requests starting with /admin
const token = req.headers.authorization;
if (token) {
next();
} else {
res.status(401).send('Unauthorized');
}
});
Route-Level Middleware
Middleware can be applied to specific routes by passing them as arguments before the final route handler.
const auth = (req, res, next) => {
// Auth logic
next();
};
app.get('/protected', auth, (req, res) => {
res.json({ message: "This is protected data" });
});
Async Middleware
Newgate supports async/await in middleware functions.
app.use(async (req, res, next) => {
try {
const user = await db.getUser(req.headers.userid);
req.user = user;
next();
} catch (err) {
next(err);
}
});
Error Handling Middleware
Error-handling middleware functions are defined in the same way as other
middleware functions, except they have four arguments instead of three:
(err, req, res, next).
app.useError((err, req, res, next) => {
console.error(err.stack);
res.status(500).send('Something broke!');
});
Notice the use of app.useError to register error handlers. This
ensures they are treated correctly by the framework's error propagation mechanism.