Node.js: Code Outside the Browser / HTTP Module-Creating a Web Server (No Express)

Setting headers and status codes

🚦 Headers & Status Codes

Headers tell the browser how to interpret the response β€” is it HTML, JSON, plain text? Status codes tell it whether the request actually succeeded, failed, or something else happened.

// index.js
import { createServer } from 'node:http';

const server = createServer((req, res) => {
  res.statusCode = 200; // OK
  res.setHeader('Content-Type', 'text/plain');
  res.end('Everything is working fine!');
});

server.listen(3000, () => {
  console.log('Header + Status Code example: <http://localhost:3000>');
});
  • res.statusCode = 200 sets the response status β€” 200 means "OK, the request succeeded." It's set separately from the body content.

  • res.setHeader(name, value) attaches metadata to the response β€” here, telling the browser to expect plain text.

  • Both of these need to be set before res.end() is called β€” once the response starts sending, headers and status code can no longer change.

πŸ’» Terminal output:

Header + Status Code example: <http://localhost:3000>

🌐 Browser output β€” visiting http://localhost:3000 shows:

Everything is working fine!

(Status: 200 OK, visible in your browser's dev tools under the Network tab.)


✨ Shorthand: res.writeHead()

Setting the status code and headers separately works, but res.writeHead() combines both into a single call.

res.writeHead(200, { 'Content-Type': 'text/plain' });

This one line does what res.statusCode = 200 + res.setHeader(...) did together:

  • πŸ”’ Sets the status code (200)

  • πŸ“‹ Sends the headers, as an object of key-value pairs

// index.js
import { createServer } from 'node:http';

const server = createServer((req, res) => {
  res.writeHead(200, { 'Content-Type': 'text/plain' });
  res.end('Everything is working fine!');
});

server.listen(3000, () => {
  console.log('Shorthand example: <http://localhost:3000>');
});

Same terminal and browser output as above β€” writeHead() is just a more compact way to write the exact same response.


πŸ”’ Common Status Codes to Know

  • βœ… 200 OK β€” request succeeded

  • βž• 201 Created β€” a new resource was created (common after a POST)

  • β†ͺ️ 301 / 302 β€” the resource has moved, redirect to a new URL

  • ❌ 404 Not Found β€” no resource exists at that URL

  • 🚫 403 Forbidden β€” the client isn't allowed to access this

  • πŸ’₯ 500 Internal Server Error β€” something broke on the server's side