Nest.js Structured API Response

Balthazar
3 min readJun 20, 2024

--

Nest.js has a predefined HTTP response JSON structured as follows:

{
"statusCode": 500,
"message": "Internal server error"
}

What if we need to change the response structure to add more details or change the names or structure?
Sometimes it is necessary to define a more detailed response structure for the client (such as a front-end or other services clients).
You might think that we should write the customized structure response at the end of any controller route, or use an object to send (res.send({})) the custom response anywhere like this:

sometimes it is necessary to define a more detailed response structured to the client(maybe a front-end or other services clients).

maybe you think we should write the customized structure response at the end of any controller route or use Response object to send(res.send({})) the custom response any where like this:

response
.status(status)
.json({
statusCode: status,
timestamp: new Date().toISOString(),
path: request.url,
});

Class-Validator response conflicts with custom API response!

All of us are using it in our projects to validate the inputs, etc.
This package uses a pre-defined error structure like this:

all of us, are using class-validator in our projects to validate the inputs, etc.
this package uses a pre-defined error structure like this:

{
"statusCode": 400,
"message": [
{
"property": "firstName",
"message": "firstName must be longer than or equal to 1 characters"
}
],
"error": "Bad Request"
}

When using this package in your code, I recommend using an API response structure that is compatible with the class-validator response structure. The “property” can be utilized on the client-side to display errors in the appropriate position (e.g. under the “property”).

Server-side Multi-lang API Response

In multi-language platforms, there are instances where errors or messages should be generated by the server-side, and the client-side should simply display the message received from the server. In such cases, the API response should include messages with a property field that guides the client in displaying the message at the appropriate location.

How to define a custom response structure?

Let’s solve it by writing DRY code, reducing complexity, and making our code maintainable and developable.

Lets Magic 🪄

Let’s find a good way to define custom responses that are compatible with Multi-lang and class-validator:

  1. define API Response Type:
export class messagesType {
message: string
property:string
}
export class ApiResponseDto<T> {
statusCode: number;
messages: messagesType[] | [];
data: T;
}

Use a generic type to handle the response.dataand make the message an array containing the message and property field.

2. in utils service or anywhere you know can be better define this method:

apiResponse<T>(statusCode: number, data: any = null, message: {message:string,property:string}[] | [] = []): ApiResponseDto<T> {
return {
statusCode,
message,
data,
};
}

this method creates an API response structure and returns it, you can add validation, sanitization, or anything you want.

3. now use the method in the controller to return:

return this.utilsService.apiResponse(
HttpStatus.OK,
functionReult,
[{message:"email subscribed to newsletter",property:"email"}]
)

4. you can add any data like timeStamp, route, etc. to apiResponseDto ✌️

Now enjoy the result of your API response ❤️.
Feel free to ask any questions and comment with your opinion about the API response structure to make it better.

--

--