0
0
Node.jsframework~8 mins

Creating a basic HTTP server in Node.js - Performance Optimization Steps

Choose your learning style9 modes available
Performance: Creating a basic HTTP server
MEDIUM IMPACT
This concept affects the initial server response time and how quickly the browser receives the first byte of content.
Serving a simple HTML page with Node.js
Node.js
import http from 'http';

const server = http.createServer((req, res) => {
  res.writeHead(200, {'Content-Type': 'text/html'});
  function writeLines(i) {
    let ok = true;
    while (i < 10000 && ok) {
      ok = res.write(`<p>Line ${i}</p>`);
      i++;
    }
    if (i < 10000) {
      res.once('drain', () => writeLines(i));
    } else {
      res.end();
    }
  }
  writeLines(0);
});

server.listen(3000);
Streaming the response in chunks avoids blocking the event loop and starts sending data earlier.
📈 Performance GainStarts sending bytes immediately, reducing time to first byte and improving LCP.
Serving a simple HTML page with Node.js
Node.js
import http from 'http';

const server = http.createServer((req, res) => {
  let html = '';
  for (let i = 0; i < 10000; i++) {
    html += '<p>Line ' + i + '</p>';
  }
  res.writeHead(200, {'Content-Type': 'text/html'});
  res.end(html);
});

server.listen(3000);
Building a large HTML string synchronously blocks the event loop and delays sending the response.
📉 Performance CostBlocks event loop for 50-100ms depending on CPU, delaying first byte and LCP.
Performance Comparison
PatternDOM OperationsReflowsPaint CostVerdict
Synchronous large string build before responseN/A (server-side)N/AN/A[X] Bad
Streaming response in chunksN/A (server-side)N/AN/A[OK] Good
Rendering Pipeline
The server sends the HTTP response which the browser receives and parses. Faster server response means the browser can start rendering sooner.
Network
First Byte
HTML Parsing
Rendering
⚠️ BottleneckServer-side blocking operations delay the first byte, slowing LCP.
Core Web Vital Affected
LCP
This concept affects the initial server response time and how quickly the browser receives the first byte of content.
Optimization Tips
1Avoid heavy synchronous processing before sending response.
2Stream response data in chunks to start sending early.
3Monitor Time to First Byte (TTFB) to gauge server response speed.
Performance Quiz - 3 Questions
Test your performance knowledge
What server behavior improves the Largest Contentful Paint (LCP) when creating a basic HTTP server?
ABuilding the entire response string before sending
BSending the response in small chunks as soon as possible
CDelaying response until all data is ready
DUsing synchronous blocking code to prepare response
DevTools: Network
How to check: Open DevTools, go to Network tab, reload page, and check the 'Time to First Byte' (TTFB) for the server response.
What to look for: Lower TTFB indicates faster server response and better LCP performance.