I have a NestJS route which sends back in response, a JSON not well formatted (like minified), I want to make this JSON easier to read, like a JSON prettier or JSON formatted, Do someone knows how to do it in NestJS ? I accept answers for other NodeJS frameworks like Express, maybe it will work in NestJS too...
Make a NestJS route send in response a pretty formatted JSON
3.4k views Asked by VersifiXion AtThere are 5 answers

While you shouldn't do it in prod as mentioned above, there's number of cases where it makes a lot of sense (e.g. in dev env). You can achieve this in a bit hacky way:
- Access
express
instance inside nest through breaking abstraction. It's not exposed onINest
interface, so you'll need to cast it toany
type to bypass Typescript check - Set undocumented
express
property"json spaces"
, which will set formatting for all JSON responses over the app
const app = await NestFactory.create(AppModule);
if (process.env.NODE_ENV === 'development') {
(app as any).httpAdapter.instance.set('json spaces', 2);
}
await app.listen(3000);

- Define return type
string
on your controller - Set the
Content-Type: application/json
response header - Use
JSON.stringify
to format your object with whitespace
Example controller code:
import { Controller, Get, Header } from '@nestjs/common';
@Controller('diagnostics')
export class DiagnosticsController {
@Get()
@Header('Content-Type', 'application/json')
findAll(): string {
const statusCode = 200;
const statusText = 'OK';
const info = {
self: 'NestJS Diagnostics Report',
status: {
statusCode,
statusText,
},
};
return JSON.stringify(info, null, 2);
}
}

Prettifying the JSON response should be the responsibility of the client, not the server. Otherwise you could be sending a lot of white space which will bloat the response size and could lead to a crash due to having a response too large. If you are using something like Postman, it should be easy to prettify it, I think Postman might do it by default. If you are looking at the response in some web browser, you could use JSON.parse()
on the response and it should make the response an actual JSON which console.log()
would then print in a pretty way.

You should try https://www.postman.com or https://insomnia.rest/. It can save you a lot of time when it comes to testing an API.
It works for me: