Routes and responses

Negotiate HTML and JSON

Keep representation logic explicit when one application serves pages and an API.

9 minute lesson

~~~

The form flow redirects after a successful POST, while the API returns JSON and a location header. This is a small part of an Express 5 notes application with an HTML interface, a JSON API, sessions, tests, and production failure handling, but the boundary it creates affects everything that follows.

The same underlying note can be rendered as HTML or serialized as JSON, but redirects and API responses have different client expectations. The useful target is not encyclopedic coverage. Make one deliberate choice, observe its consequences, and know which requirement would make you revise it.

Watch for one shortcut in particular: trying to guess the client type from a fragile user-agent string. It makes later failures harder to locate. Instead, use separate routes or explicit content negotiation and keep the domain operation independent of rendering. Prefer an implementation you can explain from the outside before optimizing it.

Keep the wider goal in view: Design routes that match intentionally, parse input from the correct location, and return one complete response. A short observation with concrete evidence is more useful than a confident sentence with no reproduction path.

Exercise the same create operation from a browser form and a JSON client, then compare the two response contracts. Hand the result to someone else and see whether the behavior is clear without an oral explanation.

Lesson completed

Take this course offline

Get every free book and course as PDF and EPUB files.

Get the download library →