Skip to content
Tutorials Center
My learning

Topics

Lesson 16 of 43 ยท Request and Response

The Response Object

Learn the Express response object: res.send, res.json, res.status, sendStatus, redirect, headers and type, chaining, and the headers-already-sent error.

Every route handler gets a res object, and everything your server says to the client goes through it. In Express, res is Node's own http.ServerResponse with a set of friendly helpers added on top: one call to send JSON, one to redirect, one to set a status code. This lesson walks through the helpers you will use every day, and the one mistake almost everyone makes at least once.

Real Express code in this lesson is read-only, because npm is not available in the browser. The runnable examples use our mini Express stand-in plus a few small helpers that copy how the real ones behave. Each example says which part is real and which is stand-in.

The helpers at a glance

Send a body

res.send Text, HTML, a Buffer or an object.
res.json Serialize a value as JSON.
res.end Finish with no helper magic.
1 / 3

Sending a body: send, json and end

res.send() is the all-purpose helper. What it does depends on the value you pass:

JavaScript
app.get('/text', (req, res) => {
  res.send('plain text');            // Content-Type: text/html
});

app.get('/html', (req, res) => {
  res.send('<h1>Hello</h1>');        // Content-Type: text/html
});

app.get('/object', (req, res) => {
  res.send({ ok: true });            // an object is sent as JSON
});

app.get('/bytes', (req, res) => {
  res.send(Buffer.from('abc'));      // Content-Type: application/octet-stream
});

A string becomes text/html; charset=utf-8 unless you already set a type, a Buffer becomes application/octet-stream, and an object or array is passed to res.json. Real res.send also calculates an ETag header so browsers can cache; Cookies and Headers explains that.

res.json() is the explicit form for APIs. Prefer it when you mean JSON, because the intent is clear and null, numbers and strings are serialized as valid JSON too:

JavaScript
app.get('/api/user', (req, res) => {
  res.json({ id: 1, name: 'Mina' });
});

res.end() is Node's own method. It finishes the response with no automatic headers. Use it for an empty answer, such as a 204 No Content:

JavaScript
app.delete('/api/items/:id', (req, res) => {
  res.status(204).end();
});

Status codes: status and sendStatus

res.status(code) only sets the code and returns res, so you chain a sender after it:

JavaScript
res.status(201).json({ id: 42 });
res.status(404).send('No such page');

Because it returns res, the chain reads like a sentence. In Express 5, res.status() throws if you give it something that is not an integer from 100 to 999, which catches typos such as res.status('ok') early.

res.sendStatus(code) sets the code and sends the standard text for it as the body:

JavaScript
res.sendStatus(404);   // 404, body: Not Found
res.sendStatus(204);   // 204, empty
res.sendStatus(418);   // 418, body: I'm a Teapot

It is handy for quick answers, but an API usually wants a JSON body, so res.status(404).json({ error: 'not found' }) is more common. For a list of codes and when to use them, see Designing a REST API.

Headers: set, get, append and type

JavaScript
res.set('X-Powered-By-Me', 'tutorial');            // one header
res.set({ 'Cache-Control': 'no-store', 'X-Debug': '1' }); // several
res.append('Link', '</next>; rel="next"');         // add without replacing
res.get('Cache-Control');                          // read what you set
res.type('json');                                  // Content-Type: application/json
res.type('.html');                                 // text/html
res.type('image/png');                             // a full MIME type works too

Header names are case-insensitive. Set headers before you send the body, because the headers go out with the first bytes of the response.

Redirects

res.redirect() sends a Location header with a redirect status. The default is 302 Found; pass a code first to choose another:

JavaScript
res.redirect('/login');                    // 302
res.redirect(301, '/new-address');         // permanent
res.redirect(303, '/thanks');              // "see other", used after POST

Use 301 or 308 for permanent moves (search engines update their links), and 303 or 302 after a form submit. The old res.redirect('back') was removed in Express 5; read the Referer header yourself, or use req.get('Referrer') || '/'.

A redirect target taken from user input, such as ?next= in a login link, can send visitors to another site. Only redirect to paths you checked, for example ones that start with a single /.

Headers can only be sent once

HTTP sends the status line and headers first, then the body. After the first res.send, res.json or res.end, the headers are gone and cannot be changed. Trying again raises ERR_HTTP_HEADERS_SENT ("Cannot set headers after they are sent to the client"). The typical cause is forgetting a return:

JavaScript
app.get('/user/:id', (req, res) => {
  if (!req.query.token) {
    res.status(401).json({ error: 'token required' });   // missing return!
  }
  res.json({ secret: true });                            // runs too: error
});

The fix is to return right after a response in an early exit:

JavaScript
if (!req.query.token) {
  return res.status(401).json({ error: 'token required' });
}

You can check res.headersSent to see whether a response has started, which matters inside error handlers.

A runnable stand-in

The stand-in res only has status, json and send. This example adds copies of set, type, sendStatus and redirect as a middleware layer. They are written by hand for this lesson and are much simpler than the real ones, but they behave the same for these cases. The helper function prints status, selected headers and body so you can see exactly what a client receives.

Node.js Status, headers, type and redirect

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Because the stand-in's own send always writes text/plain, the last route sets the type and calls end. Look at the styles: /created chains status, set and json; /gone lets sendStatus supply the text Gone; /old has an empty body and only a location header, which is all a redirect needs.

Seeing the headers-sent error

The real error comes from Node itself, so we can reproduce it exactly without Express. The stand-in's json helper calls setHeader, which Node refuses after the headers went out. The try/catch shows the error code you would see in your logs.

Node.js What 'headers already sent' looks like

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

In /oops the first response goes out and the second attempt fails with ERR_HTTP_HEADERS_SENT. In Express 5 an uncaught error like this reaches your error handler, but the client has already received the first reply, so the best fix is simply to return.

The helpers so far cover most days. Five more solve specific problems, and you will meet them in code reviews and interviews.

res.format(): answer in the format the client asked for. It wraps the req.accepts switch from The Request Object. You pass an object whose keys are types (a MIME type such as 'text/html', or a short name like 'json', 'html', 'text') and whose values are functions. Express picks the best match for the Accept header, sets the Content-Type and Vary: Accept for you and calls that function. A default key handles everything else. With no match and no default, Express sends the error 406 Not Acceptable to your error handler.

JavaScript
// Real Express
app.get('/report', (req, res) => {
  res.format({
    text: () => res.send('Total: 3'),
    html: () => res.send('<p>Total: <b>3</b></p>'),
    json: () => res.json({ total: 3 }),
    default: () => res.status(406).send('Not Acceptable'),
  });
});

res.links(): pagination links in a header. Instead of putting next and previous URLs inside the JSON body, APIs can send them in the standard Link header (the convention used by GitHub's API). res.links({ next: url, last: url }) builds Link: <url>; rel="next", <url>; rel="last". Calling it again adds more links to the same header. Clients follow the rel="next" link until it disappears.

res.location(): set the Location header without redirecting. res.redirect() sets Location and a 3xx status. After a successful POST, the correct response is 201 Created with a Location header pointing to the new resource, and no redirect: res.location('/books/7').status(201).json(book). res.location() also percent-encodes characters that are not valid in a URL. (The old special value 'back' was removed in Express 5; read the Referer header yourself if you need it, and validate it.)

res.vary(): tell caches what the response depends on. If the body changes with a request header (Accept, Accept-Language, Accept-Encoding, Cookie), a shared cache must not serve one client's version to another. res.vary('Accept-Language') adds the field name to the Vary header without duplicates. res.format and compression middleware already call it for the headers they use, but custom logic that branches on a header must do it manually, or a CDN may cache the wrong variant.

res.jsonp(): JSON wrapped in a callback. Before CORS existed, JavaScript on one site could only read data from another site by loading it as a <script> tag, so the server returned JSON padded with a function call: callback({"a":1}). res.jsonp(data) reads the callback name from the query string (parameter callback, configurable with the jsonp callback name setting), checks that the name contains only safe characters, escapes the characters that break JavaScript, and sends text/javascript with X-Content-Type-Options: nosniff. When there is no callback parameter, it behaves like res.json.

JSONP is a legacy technique. Any website can include your endpoint in a script tag and read the response, using the visitor's cookies, so it must never return private data. Use CORS for cross-origin API access (Third-Party Middleware) and res.json for everything else.

Watching all five

The program below implements simplified versions of the five helpers (the real ones live in Express's response prototype) and serves them over real HTTP. Use it to see the headers each helper produces.

Node.js res.format, links, location, vary and jsonp

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Look at what each helper did. format picked JSON for the first request and HTML (higher q) for the second, set the content type, and added Vary: Accept. With no match and no default, the error reached the error handler as a 406 listing the supported types. links merged two calls into one Link header. location kept the status at 201 and encoded the space in the URL. vary listed each field once, whatever the capitalization. jsonp wrapped the JSON in show(...), escaped the invisible U+2028 line separator, and stripped the characters from a malicious callback name (alert(1);evil became alert1evil, which is harmless text rather than code); without a callback it fell back to plain JSON.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does res.status(404) do on its own?

    res.status only sets the code. You still need send, json or end to finish the response.
  2. 2. Which call sends a 204 response with no body?

    A 204 has no body, so set the status and finish with end(). res.sendStatus(204) also works.
  3. 3. What does res.sendStatus(404) send as the body?

    sendStatus sets the code and uses the standard reason phrase as a plain text body.
  4. 4. Why does a handler need "return res.status(401).json(...)" in an early exit?

    Execution continues after the first send. A second send raises ERR_HTTP_HEADERS_SENT.

Summary

  • res.send picks a content type from the value; res.json always sends JSON; res.end finishes with no extras.
  • res.status(code) sets the code and chains; res.sendStatus(code) also sends the standard text.
  • res.set, res.append, res.get and res.type handle headers and content type.
  • res.redirect defaults to 302; choose 301/308 for permanent moves and validate user-supplied targets.
  • Send exactly one response per request and return after early exits.

Next: Cookies and Headers.