tezvyn:

res.send vs res.json vs res.end

AI-drafted, machine-checkedSource: interviewintermediate
WHAT IT TESTS

how Express sends responses.

OUTLINE

send is flexible and sets content type by type, json serializes and sets JSON content type, end is the raw http terminator with no body helpers.

RED FLAG

using res.end to return an object or claiming they.

WHAT THIS TESTS This checks understanding of how Express finalizes responses and the convenience layers it adds over the raw http response, including content-type handling and serialization.

A GOOD ANSWER COVERS res.send is the versatile high-level method: pass it a string, Buffer, or object, and it infers the appropriate Content-Type, sets the content length, and finalizes the response. If you pass an object or array, it serializes to JSON automatically. res.json is purpose-built for JSON: it always sets Content-Type to application/json and serializes the argument with JSON stringification, including respecting settings like pretty-printing; it also correctly serializes values such as null that plain send handles differently, making it the clear choice for API responses. res.end is the low-level method inherited from the core http response. It optionally writes a final chunk of raw data and ends the response, but it does no content-type detection and no serialization, so it is used when you have no body, such as ending a 204 response, or when you have already streamed data.

COMMON WRONG ANSWERS Passing an object to res.end, which produces [object Object] or an error rather than JSON. Believing res.send and res.json are truly identical, ignoring json's explicit content type and serialization semantics. Calling res.end after res.send, double-finalizing the response.

LIKELY FOLLOW-UPS What happens if you call two terminating methods on one response. How does res.json handle null versus res.send. How do you set a status before sending.

ONE CONCRETE EXAMPLE For an API you write res.json({ ok: true }), guaranteeing application/json and proper serialization. For a plain text page res.send('Welcome') sets text/html. For a delete with no body you use res.status(204).end(), sending no payload. Passing the object to res.end({ ok: true }) instead would fail to serialize correctly.

Read the original → expressjs.com

Get five bites like this every day.

Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.