Introduction
Routing is the process of determining how a server responds to different client requests based on the requested URL and HTTP method. In Node.js, the built-in http module allows you to implement basic routing without relying on external frameworks. Understanding manual routing provides a strong foundation before learning web frameworks like Express.
Information
What is Routing?
A route defines the logic that should execute when a client requests a specific URL. Each route usually consists of:
- A URL path (such as / or /about)
- An HTTP method (such as GET or POST)
- A response returned by the server
Understanding the Request Object
The request object contains information needed for routing. The two most commonly used properties are:
| Property | Description |
|---|---|
| req.url | Contains the requested URL path. |
| req.method | Contains the HTTP request method. |
Inspecting request information
const http = require("http");
const server = http.createServer((req, res) => {
console.log(req.url);
console.log(req.method);
res.end("Request received");
});
server.listen(3000);Creating a Basic Router
The simplest way to implement routing is by using conditional statements that compare the request URL.
Routing using if...else
const http = require("http");
const server = http.createServer((req, res) => {
if (req.url === "/") {
res.writeHead(200, {
"Content-Type": "text/plain"
});
res.end("Welcome to the Home Page");
} else if (req.url === "/about") {
res.writeHead(200, {
"Content-Type": "text/plain"
});
res.end("About Us");
} else if (req.url === "/contact") {
res.writeHead(200, {
"Content-Type": "text/plain"
});
res.end("Contact Page");
} else {
res.writeHead(404, {
"Content-Type": "text/plain"
});
res.end("404 - Page Not Found");
}
});
server.listen(3000, () => {
console.log("Server running on port 3000");
});Route Flow
Routing Based on HTTP Methods
In many applications, the same URL behaves differently depending on the HTTP method. For example, a GET request retrieves data, while a POST request submits new data.
Routing by URL and HTTP method
const http = require("http");
const server = http.createServer((req, res) => {
if (req.url === "/users" && req.method === "GET") {
res.writeHead(200, {
"Content-Type": "text/plain"
});
res.end("Fetching users");
} else if (req.url === "/users" && req.method === "POST") {
res.writeHead(201, {
"Content-Type": "text/plain"
});
res.end("Creating a new user");
} else {
res.writeHead(404, {
"Content-Type": "text/plain"
});
res.end("Route not found");
}
});
server.listen(3000);Serving HTML Pages
Routes can return HTML content instead of plain text by setting the appropriate Content-Type header.
Returning HTML
if (req.url === "/") {
res.writeHead(200, {
"Content-Type": "text/html"
});
res.end("<h1>Welcome to the Home Page</h1>");
}Returning JSON Responses
JSON responses are commonly used when building APIs.
Returning JSON data
if (req.url === "/api") {
res.writeHead(200, {
"Content-Type": "application/json"
});
res.end(JSON.stringify({
success: true,
message: "API is working"
}));
}Handling 404 Errors
Every server should handle unknown routes gracefully by returning a 404 Not Found response.
404 handler
res.writeHead(404, {
"Content-Type": "text/plain"
});
res.end("404 - Page Not Found");Important
Common HTTP Status Codes
| Status Code | Meaning | Typical Usage |
|---|---|---|
| 200 | OK | Successful request |
| 201 | Created | Resource successfully created |
| 400 | Bad Request | Invalid client request |
| 404 | Not Found | Requested route does not exist |
| 500 | Internal Server Error | Unexpected server error |
Testing Routes
- Start the server using node server.js.
- Open a web browser or an API testing tool.
- Visit http://localhost:3000/.
- Test additional routes like /about, /contact, and /api.
- Request an unknown URL to verify the 404 response.
Example Request Flow
Advantages of Basic Routing
- Simple to understand for beginners.
- No external dependencies are required.
- Provides insight into how web frameworks implement routing.
- Suitable for small applications and learning purposes.
Limitations
- Large numbers of routes become difficult to maintain.
- Dynamic routes require additional parsing logic.
- No built-in middleware support.
- Manual handling of request parsing and responses.
Warning
Best Practices
- Always check both req.url and req.method when appropriate.
- Set the correct Content-Type for every response.
- Return meaningful HTTP status codes.
- Include a default 404 handler.
- Keep routing logic clean and separate from business logic as your application grows.
Best Practice
Official Documentation
Node.js HTTP Module Documentation