Routing, middleware, validation, auth, structure
Practise these as flashcards. One or two lines each; the ones you miss come back first.
Start freeMiddleware in Express is a function that processes requests and responses. It can modify the request, perform actions like logging or authentication, and then call next() to pass control to the next middleware. The chain continues until a response is sent or an error occurs.
Error middleware in Express is defined with four parameters: err, req, res, next. When an error is passed to next(err), Express routes the request to the error middleware, where you can send an error response or log the issue.
I use libraries like express-validator to define validation rules as middleware. After validation, I check for errors with validationResult(req) and return a 400 response if validation fails, ensuring only valid data is processed.
A NestJS controller is a class decorated with @Controller that handles incoming HTTP requests. It defines route handlers for different endpoints and delegates business logic to services or providers.
NestJS uses dependency injection to manage the lifecycle and dependencies of classes. Providers are marked with @Injectable() and injected into controllers or other providers via constructor parameters. This promotes modularity and testability.
I use Passport.js with the JWT strategy. On login, I issue a JWT signed with a secret. For protected routes, Passport verifies the token and attaches the user to the request. This allows stateless authentication and easy token validation.
To avoid N+1 queries, I use Prisma's include option to fetch related data in a single query. For example, fetching users with their posts avoids multiple queries and improves performance.
I use Supertest to send HTTP requests to the Express app and Jest to assert the responses. This allows me to test endpoints end-to-end, including status codes, response bodies, and error handling.
Modules in NestJS group related controllers, providers, and services. They help organize code, encapsulate functionality, and enable lazy loading or feature separation. Every NestJS app has at least one root module.
I use the cors middleware and configure allowed origins, methods, and headers. For example, app.use(cors({ origin: 'https://mydomain.com' })) restricts access to specific domains.
I define DTOs with decorators like @IsEmail and apply validation pipes globally or per route. The pipe automatically validates incoming data and returns a 400 error if validation fails, keeping controllers clean.
I organize the app into feature modules, each with its own controllers and providers. Shared logic goes into common modules. I use dependency injection to keep components decoupled and leverage middleware and guards for cross-cutting concerns like auth and logging.