Status Codes and Semantic Correctness
In this lesson, you’ll learn how to map your Node.js application’s server-side logic to the correct HTTP status codes to ensure meaningful communication between client and server.
When you build a server, your code logic determines if an operation was successful or why it failed. Simply sending back a 200 OK for every response is "semantically incorrect" because it hides the reason for a result. HTTP status codes act as a standardized vocabulary that tells the client exactly what happened.
The Logic-to-Status Mapping
Think of your server logic as a series of branches. Depending on which branch your code takes, you should choose a code from the relevant range:
- 2xx (Success): Everything went according to plan. Use
200 OKfor general success, or201 Createdspecifically when a resource (like a database entry) has been successfully generated. - 4xx (Client Error): The client sent a request that the server cannot process. For example, if a user tries to access a file that doesn't exist, you use
404 Not Found. If they send malformed data that your logic can't parse, you use400 Bad Request. - 5xx (Server Error): The client did everything right, but your server crashed or encountered an unexpected internal error. Using
500 Internal Server Errorsignals that the problem is on your end, not the user's.
Implementation Example
In a raw Node.js http server, you explicitly set these codes before sending the response:
const http = require('http');
http.createServer((req, res) => {
// Example logic: checking if a resource ID is missing
if (!req.url.includes('id')) {
res.statusCode = 400; // Semantic: Client failed to provide ID
return res.end('Bad Request: Missing ID');
}
// Example logic: simulating a successful database save
res.statusCode = 201; // Semantic: Resource created
res.end('Success: Resource Created');
}).listen(3000);
By mapping your internal "if/else" logic to these specific ranges, you enable the client to understand if they should try again, fix their request, or wait for you to fix your server.
Key Takeaway: Status codes are not arbitrary; they are the semantic contract that tells the client whether they should fix their request (4xx) or if the server failed to fulfill it (5xx).