Express is a minimal, flexible Node.js web framework for building web applications and APIs. It provides routing, middleware support, HTTP utilities, and template engine integration. Express simplifies server creation compared to using Node's built-in http module. It's lightweight and unopinionated, giving you full control over your architecture.
Middleware are functions that execute during request/response cycle. They receive (req, res, next) and can modify request/response or call next(). Middleware executes in the order defined. Types: built-in (express.json()), third-party (cors, compression), custom. Use middleware for authentication, logging, validation, and error handling.
app.use(middleware) applies middleware to all routes (or specified path). app.get(path, handler) handles GET requests to a specific route. app.use() is for middleware, app.get/post/put/delete are for route handlers. You can chain handlers: app.get(path, middleware1, middleware2, handler).
Use try/catch in async route handlers and pass errors to next(). Create error middleware: app.use((err, req, res, next) => {}). Error middleware must have 4 parameters and be defined after other middleware. Send appropriate status codes and error messages. In production, log errors and avoid exposing sensitive stack traces.
Route parameters are URL segments: /users/:id has id parameter accessed via req.params.id. Query strings are URL-encoded data: /search?q=node accessed via req.query.q. Use route parameters for resource identification, query strings for filtering/sorting. Validate and sanitize both for security.
Use middleware for authentication checks. Popular approaches: JWT (tokens in headers), sessions (store server-side), passport.js (authentication library). Create middleware: const auth = (req, res, next) => { if (token valid) next(); else res.status(401).send('Unauthorized'); }. Protect routes by adding auth middleware.
Use MVC pattern: models (data), views (templates), controllers (logic). Organize routes into separate files, use express.Router() to group related routes. Create middleware folder, utils folder, config folder. Example: routes/users.js, routes/posts.js. Keep app.js minimal with just middleware setup and route imports.
Use app.use(express.static('public')). Files in 'public' directory are served directly: /public/style.css is accessed as /style.css. Multiple static directories: app.use(express.static('public')); app.use(express.static('uploads'));. Virtual prefix: app.use('/assets', express.static('public'));