0
0
Node.jsframework~8 mins

Routing requests manually in Node.js - Performance & Optimization

Choose your learning style9 modes available
Performance: Routing requests manually
MEDIUM IMPACT
This affects server response time and how quickly the server can handle incoming HTTP requests.
Handling multiple URL routes in a Node.js server
Node.js
const http = require('http');
const routes = {
  '/': (res) => res.end('Home Page'),
  '/about': (res) => res.end('About Page'),
  '/contact': (res) => res.end('Contact Page')
};
const server = http.createServer((req, res) => {
  const handler = routes[req.url];
  if (handler) {
    handler(res);
  } else {
    res.statusCode = 404;
    res.end('Not Found');
  }
});
server.listen(3000);
Uses direct lookup in an object to find route handler, reducing checks and speeding response.
📈 Performance GainSingle lookup per request, reducing CPU time and improving response speed.
Handling multiple URL routes in a Node.js server
Node.js
const http = require('http');
const server = http.createServer((req, res) => {
  if (req.url === '/') {
    res.end('Home Page');
  } else if (req.url === '/about') {
    res.end('About Page');
  } else if (req.url === '/contact') {
    res.end('Contact Page');
  } else {
    res.statusCode = 404;
    res.end('Not Found');
  }
});
server.listen(3000);
Each request checks multiple if-else conditions sequentially, causing slower response as routes grow.
📉 Performance CostBlocks event loop longer with more routes, increasing response time linearly.
Performance Comparison
PatternDOM OperationsReflowsPaint CostVerdict
Manual if-else routingN/A (server-side)N/AN/A[X] Bad
Object lookup routingN/A (server-side)N/AN/A[OK] Good
Rendering Pipeline
Manual routing affects the server's request handling pipeline before sending response to the browser.
Request Parsing
Routing Logic
Response Generation
⚠️ BottleneckRouting Logic stage due to sequential condition checks
Optimization Tips
1Avoid long chains of if-else for routing; use direct lookup structures.
2Manual routing affects server response time, not browser rendering.
3Faster routing reduces server CPU load and improves user wait time.
Performance Quiz - 3 Questions
Test your performance knowledge
What is a main performance drawback of manual routing with many if-else statements in Node.js?
ASequential checks increase server response time as routes grow
BIt increases browser paint time
CIt causes layout shifts in the browser
DIt increases CSS selector complexity
DevTools: Network
How to check: Open DevTools, go to Network tab, reload page and check server response times for different routes.
What to look for: Look for longer server response times indicating slow routing logic.