If you're sending a JSON response from a web server to a client, you might want to format it with proper indentation. For the longest time, I thought the only way to achieve this in Express was to call the JSON.stringify() method explicitly and pass in the desired number of spaces (or other indentation, e.g. "\t" to use tabs):

app.get("/", (_req, res) => {
let code = 200;
let message = http.STATUS_CODES[code];
let data = { code, message };
res.send(JSON.stringify(data, null, 2));

A little while ago, I discovered a "json spaces" setting that you can pass into the app.set() method to accomplish the same thing:

app.set("json spaces", 2);

Internally, Express uses the second argument as the third argument to the JSON.stringify() method, just as if you called it explicitly. The benefit of the app.set() method is twofold:

  1. You don't have to explicitly call the JSON.stringify() method for every route.
  2. You're guaranteed to use consistent indentation for every route.