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

Handling different URL routes manually

🧭 Handling Different Routes

Let's say you want different pages like /, /about, and /contact β€” each with its own response.

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

const server = createServer((req, res) => {
  res.setHeader('Content-Type', 'text/plain');

  if (req.url === '/') {
    res.writeHead(200);
    res.end('Welcome to the Home Page!');
  } else if (req.url === '/about') {
    res.writeHead(200);
    res.end('This is the About Page.');
  } else if (req.url === '/contact') {
    res.writeHead(200);
    res.end('Contact us at: example@email.com');
  } else {
    res.writeHead(404);
    res.end('404 Page Not Found');
  }
});

server.listen(3000, () => {
  console.log('Server running at <http://localhost:3000>');
});
  • req.url holds the path the browser requested (/, /about, /contact, or anything else) β€” comparing it in an if/else chain is how you route different pages.

  • res.setHeader('Content-Type', 'text/plain') tells the browser what kind of content is coming, so it renders the response correctly instead of guessing.

  • res.writeHead(200) explicitly marks the response as successful β€” technically optional here since 200 is the default, but writing it makes the intent clear.

  • The fix: the unmatched-route branch now calls res.writeHead(404) before res.end(). Without it, an unknown URL still gets a 200 OK status even though the page says "Not Found" β€” which is misleading to browsers, search engines, and any code checking the response status.


▢️ Try It

  • Run node index.js

Terminal output:

Server running at <http://localhost:3000>

Now visit each route in your browser:

http://localhost:3000/

Status: 200 OK
Body:   Welcome to the Home Page!

http://localhost:3000/about

Status: 200 OK
Body:   This is the About Page.

http://localhost:3000/contact

Status: 200 OK
Body:   Contact us at: example@email.com

http://localhost:3000/anything-else

Status: 404 Not Found
Body:   404 Page Not Found

πŸ’‘ With more than a handful of routes, this if/else chain gets unwieldy fast β€” that's the problem frameworks like Express solve with proper routing.