0
0
Node.jsframework~15 mins

Routing requests manually in Node.js - Deep Dive

Choose your learning style9 modes available
Overview - Routing requests manually
What is it?
Routing requests manually means deciding how a server handles different web requests by writing code that checks the request's address and sends back the right response. Instead of using tools that do this automatically, you write the rules yourself. This helps you understand how web servers work at a basic level. It involves listening for requests, checking their paths, and sending back content or data.
Why it matters
Without routing, a server wouldn't know what to do when someone visits different pages or asks for different information. If routing didn't exist, websites would be static and unable to respond differently to each request. Manually routing helps learners see the core of how web servers work and prepares them to use or build more advanced tools later. It also helps debug problems when automatic routing fails.
Where it fits
Before learning manual routing, you should understand how HTTP requests and responses work and basic Node.js server creation. After mastering manual routing, you can learn frameworks like Express.js that automate routing and add features. This topic is a bridge between raw server basics and using powerful web frameworks.
Mental Model
Core Idea
Routing manually is like being a traffic controller who reads each request's address and directs it to the right handler to send back the correct response.
Think of it like...
Imagine a receptionist at a company who listens to visitors' requests and then tells them which office or person to visit based on what they want. The receptionist checks the visitor's purpose and guides them accordingly.
┌───────────────┐
│ Incoming HTTP │
│   Request     │
└──────┬────────┘
       │
       ▼
┌───────────────┐
│  Router Code  │
│ (checks path) │
└──────┬────────┘
       │
 ┌─────┴─────┐
 │           │
 ▼           ▼
Handler A  Handler B
 (e.g. /)   (e.g. /about)
       │           │
       ▼           ▼
┌───────────────┐
│ HTTP Response │
│   Sent Back   │
└───────────────┘
Build-Up - 7 Steps
1
FoundationCreate a basic Node.js server
🤔
Concept: Learn how to start a simple server that listens for requests.
Use Node.js built-in 'http' module to create a server. The server listens on a port and sends a simple response to every request, ignoring the request details.
Result
A server runs and responds with the same message to any request.
Understanding how to start a server is the first step to controlling how requests are handled.
2
FoundationAccess request URL and method
🤔
Concept: Learn to read the request's URL and HTTP method to know what the client wants.
Inside the server callback, use 'req.url' and 'req.method' to see the path and type of request (GET, POST, etc.). Log these to understand incoming requests.
Result
You can see in the console what URL and method each request uses.
Knowing the request details lets you decide how to respond differently.
3
IntermediateImplement simple path-based routing
🤔Before reading on: do you think checking only the URL path is enough to handle all request types correctly? Commit to your answer.
Concept: Use conditional statements to send different responses based on the request URL path.
Inside the server callback, use if-else or switch to check 'req.url'. For example, if the path is '/', send a welcome message; if '/about', send info about the site; else send a 404 message.
Result
The server responds differently depending on the URL path requested.
Routing by path is the core idea behind directing requests to the right content.
4
IntermediateHandle HTTP methods in routing
🤔Before reading on: do you think the same URL path should always respond the same way regardless of HTTP method? Commit to your answer.
Concept: Add checks for HTTP methods (GET, POST, etc.) to handle requests differently even if the URL is the same.
Extend routing logic to check both 'req.url' and 'req.method'. For example, respond with a form on GET '/contact' and process form data on POST '/contact'.
Result
The server can respond differently to the same path depending on the method used.
Understanding HTTP methods allows building interactive and dynamic web servers.
5
IntermediateServe static files manually
🤔Before reading on: do you think you can serve images or CSS files by just checking the URL path? Commit to your answer.
Concept: Learn to read files from disk and send them as responses based on the request URL.
Use Node.js 'fs' module to read files like HTML, CSS, or images. Check the URL path, map it to a file path, read the file, and send its content with the correct content-type header.
Result
The server can serve static assets like web pages and stylesheets.
Serving files manually shows how web servers deliver resources beyond simple text.
6
AdvancedManage routing with reusable functions
🤔Before reading on: do you think writing all routing logic inline is easy to maintain for many routes? Commit to your answer.
Concept: Organize routing logic into separate functions or objects to keep code clean and scalable.
Create a routing table object mapping paths and methods to handler functions. In the server callback, look up the handler and call it. This separates routing logic from response logic.
Result
Routing code is cleaner, easier to add or change routes, and more maintainable.
Structuring routing logic like this prepares you for frameworks and larger projects.
7
ExpertUnderstand limitations and scaling challenges
🤔Before reading on: do you think manual routing scales well for large applications with many routes and features? Commit to your answer.
Concept: Explore why manual routing becomes hard to maintain and how frameworks solve these problems.
Manual routing lacks features like middleware, route parameters, error handling, and performance optimizations. Frameworks like Express add these to simplify development and improve reliability.
Result
You see why manual routing is good for learning but not ideal for complex apps.
Knowing manual routing limits helps you appreciate and use frameworks effectively.
Under the Hood
When a request arrives, Node.js triggers the server's callback with request and response objects. The code reads the request's URL and method properties to decide what content to send. The response object is used to write headers and body data back to the client. This process happens asynchronously, allowing the server to handle many requests without blocking.
Why designed this way?
Node.js uses an event-driven, non-blocking model to handle many requests efficiently. Manual routing was the original way to control responses before frameworks existed. It was designed to give developers full control and understanding of request handling, though it requires more code and care.
┌───────────────┐
│ HTTP Request  │
└──────┬────────┘
       │
       ▼
┌───────────────┐
│ Node.js Event │
│  Loop triggers│
│  server code  │
└──────┬────────┘
       │
       ▼
┌───────────────┐
│ Read req.url  │
│ and req.method│
└──────┬────────┘
       │
       ▼
┌───────────────┐
│ Routing Logic │
│ (if/switch)   │
└──────┬────────┘
       │
       ▼
┌───────────────┐
│ Write Response│
│ headers/body  │
└──────┬────────┘
       │
       ▼
┌───────────────┐
│ HTTP Response │
│   Sent Back   │
└───────────────┘
Myth Busters - 4 Common Misconceptions
Quick: Do you think manual routing automatically handles query strings and URL parameters? Commit to yes or no.
Common Belief:Manual routing automatically parses query strings and URL parameters for you.
Tap to reveal reality
Reality:Manual routing only gives you the raw URL string; you must parse query strings and parameters yourself.
Why it matters:Assuming automatic parsing leads to bugs and security issues because the server might misinterpret request data.
Quick: Do you think manual routing can handle thousands of routes efficiently without extra tools? Commit to yes or no.
Common Belief:Manual routing scales well to any number of routes without performance problems.
Tap to reveal reality
Reality:Manual routing with many if-else checks becomes slow and hard to maintain; specialized routing algorithms or frameworks are needed.
Why it matters:Ignoring this causes slow servers and unmanageable code in large applications.
Quick: Do you think manual routing automatically handles errors like 404 or server crashes? Commit to yes or no.
Common Belief:Manual routing automatically sends 404 or error pages when something goes wrong.
Tap to reveal reality
Reality:You must explicitly code error handling; otherwise, the server may crash or send confusing responses.
Why it matters:Missing error handling leads to poor user experience and unstable servers.
Quick: Do you think manual routing is obsolete and useless today? Commit to yes or no.
Common Belief:Manual routing is outdated and has no practical use anymore.
Tap to reveal reality
Reality:Manual routing is essential for learning, debugging, and understanding how frameworks work under the hood.
Why it matters:Ignoring manual routing knowledge makes it harder to fix problems or customize behavior in real projects.
Expert Zone
1
Manual routing requires careful handling of asynchronous operations to avoid blocking the event loop.
2
Proper content-type headers must be set manually to ensure browsers interpret responses correctly.
3
Manual routing exposes the developer to security risks like path traversal if file serving is not carefully implemented.
When NOT to use
Manual routing is not suitable for large or complex applications where features like middleware, route parameters, and error handling are needed. Instead, use frameworks like Express.js or Fastify that provide these features out of the box.
Production Patterns
In production, manual routing is often used only for very simple servers or learning. Professionals use routing tables, middleware chains, and modular route handlers within frameworks to organize code and handle complex scenarios efficiently.
Connections
HTTP Protocol
Manual routing builds directly on understanding HTTP requests and responses.
Knowing HTTP basics helps you understand why routing checks URL and method to decide responses.
State Machine Design
Routing logic can be seen as a state machine deciding next steps based on input (URL and method).
Viewing routing as a state machine clarifies how to handle complex flows and transitions in request handling.
Traffic Control Systems
Routing requests manually is like directing traffic flow based on signals and destinations.
Understanding traffic control helps grasp how routing directs requests efficiently and safely.
Common Pitfalls
#1Ignoring HTTP method differences and responding the same way to GET and POST.
Wrong approach:if (req.url === '/contact') { res.end('Contact page'); }
Correct approach:if (req.url === '/contact' && req.method === 'GET') { res.end('Contact form'); } else if (req.url === '/contact' && req.method === 'POST') { res.end('Form submitted'); }
Root cause:Not understanding that HTTP methods represent different actions requiring different responses.
#2Serving files without setting correct content-type headers.
Wrong approach:fs.readFile('style.css', (err, data) => { res.end(data); });
Correct approach:fs.readFile('style.css', (err, data) => { res.setHeader('Content-Type', 'text/css'); res.end(data); });
Root cause:Not knowing browsers rely on content-type headers to render files properly.
#3Writing all routing logic inline without separation.
Wrong approach:http.createServer((req, res) => { if (req.url === '/') { res.end('Home'); } else if (req.url === '/about') { res.end('About'); } else if (req.url === '/contact') { res.end('Contact'); } // many more routes inline });
Correct approach:const routes = { '/': (req, res) => res.end('Home'), '/about': (req, res) => res.end('About'), '/contact': (req, res) => res.end('Contact') }; http.createServer((req, res) => { const handler = routes[req.url]; if (handler) handler(req, res); else { res.statusCode = 404; res.end('Not found'); } });
Root cause:Not appreciating the need for code organization and scalability.
Key Takeaways
Manual routing means writing code to check each request's URL and method to decide the response.
It helps you understand how web servers work before using frameworks that automate routing.
Manual routing requires careful handling of request details, response headers, and errors.
While good for learning, manual routing is hard to scale and maintain for large apps.
Knowing manual routing deeply improves your ability to debug and customize web servers.