Build a small JSON endpoint

Lesson 3 of 4 · 2 min read

Validate a query parameter

Define the route, allowed method, and shape of a valid name at the request boundary.

Demo lesson · not author-approved.

Define the contract

The endpoint accepts GET /hello with an optional name parameter. Missing names default to reader. An explicitly empty name, repeated parameter, or name longer than 60 characters is invalid.

Replace the handler

Replace all of handler.js with:

export function handler(request, response) {
  const send = (status, body) => {
    response.writeHead(status, { 'Content-Type': 'application/json; charset=utf-8' });
    response.end(JSON.stringify(body));
  };

  const url = new URL(request.url, 'http://localhost');
  if (url.pathname !== '/hello') return send(404, { error: 'Not found' });
  if (request.method !== 'GET') {
    response.setHeader('Allow', 'GET');
    return send(405, { error: 'Method not allowed' });
  }

  const values = url.searchParams.getAll('name');
  const name = values.length ? values[0].trim() : 'reader';
  if (values.length > 1 || name.length === 0 || name.length > 60) {
    return send(400, { error: 'Use one name between 1 and 60 characters' });
  }
  return send(200, { message: `Hello, ${name}!` });
}

The URL constructor decodes query parameters. Using getAll lets us distinguish one name from repeated names rather than silently accepting the first.

Try both outcomes

Restart with npm start. Open http://127.0.0.1:3000/hello?name=Ada and then http://127.0.0.1:3000/hello?name=.

The first returns a greeting; the second returns an error. Your browser displays both as JSON, so use its Network panel to inspect the different status codes.

Keep the scope honest

The length check uses JavaScript string length, not human-perceived characters. This is sufficient for this exercise, but a real internationalized product should define its counting policy deliberately. The endpoint is also local-only and has no abuse protection.