CodingNeed.

3 · Reliability and delivery · 30 MIN

HTTP routing and explicit responses

Every request needs a defined route, status and completion path.

The built-in HTTP server exposes a request stream and a response writer. A URL object parses the pathname independently of query strings. Route on both method and path, set an appropriate content type and always finish the response. This local example provides only read-only routes, making it useful for learning before adding body parsing and authentication. Binding to loopback keeps the development server local. Production hosting needs its own process lifecycle, proxy configuration, limits and monitoring.

Verify status and JSON content type.

Read the example

import {createServer} from 'node:http';
const server=createServer((req,res)=>{
  const path=new URL(req.url??'/', 'http://localhost').pathname;
  res.setHeader('Content-Type','application/json; charset=utf-8');
  if(req.method==='GET'&&path==='/health'){
    res.writeHead(200);res.end(JSON.stringify({ok:true}));return;
  }
  res.writeHead(404);res.end(JSON.stringify({error:'Not found'}));
});
server.listen(3000,'127.0.0.1',()=>console.log('Listening on port 3000'));
Check the expected output
GET http://127.0.0.1:3000/health returns 200 and {"ok":true}; an unknown path returns 404.

Your challenge

Add GET /courses with a small public dataset, HEAD handling and an explicit method-not-allowed response for known paths.

Solution cost: O(1) routing for this fixed route set. time · O(1) route state, excluding active connections. space

Common trap

A response that never calls end can leave a client waiting until timeout.

Study the project implementation
import {createServer} from 'node:http';
const server=createServer((req,res)=>{
  const path=new URL(req.url??'/', 'http://localhost').pathname;
  res.setHeader('Content-Type','application/json; charset=utf-8');
  if(req.method==='GET'&&path==='/health'){
    res.writeHead(200);res.end(JSON.stringify({ok:true}));return;
  }
  res.writeHead(404);res.end(JSON.stringify({error:'Not found'}));
});
server.listen(3000,'127.0.0.1',()=>console.log('Listening on port 3000'));

Further reading: Official documentation

Next lesson: Project · Test a service contract

Essential cookies keep your account signed in. Optional analytics is not configured on this site. Your choice does not affect access to lessons.

Read the Privacy Policy. You can change this choice in the footer.