Describe the typical backend stack: how do you manage routing, validation, authorization, error handling, logging?
sobes.tech AI
Answer from AI
In a typical Node.js backend, the Express framework is often used for routing management. Routing is organized through defining routes with HTTP methods (GET, POST, etc.), for example:
const express = require('express');
const app = express();
app.get('/users/:id', (req, res) => {
// request handling
});
For data validation, libraries like Joi or express-validator are often used, which allow you to describe a data schema and validate incoming requests before processing.
Authorization is implemented via middleware, for example, using JWT. Middleware checks for the presence and validity of the token, as well as user access rights.
Error handling is usually centralized through middleware with four parameters (err, req, res, next), where errors can be logged and correct responses sent to the client.
Logging is done using libraries like Winston or Pino, which allow saving logs to files, databases, or external services, and configuring logging levels (info, error, debug).
Example middleware for authorization and error handling:
// Authorization
function authMiddleware(req, res, next) {
const token = req.headers.authorization;
if (!token) return res.status(401).send('Unauthorized');
// Token validation...
next();
}
// Error handling
app.use((err, req, res, next) => {
console.error(err);
res.status(500).json({ message: 'Internal Server Error' });
});