0
0
Expressframework~8 mins

DTO pattern for data transfer in Express - Performance & Optimization

Choose your learning style9 modes available
Performance: DTO pattern for data transfer
MEDIUM IMPACT
This pattern affects how data is prepared and sent over the network, impacting response size and serialization time.
Sending user data in an API response
Express
class UserDTO {
  constructor(user) {
    this.id = user.id;
    this.name = user.name;
    this.email = user.email;
  }
}

app.get('/user', (req, res) => {
  const user = getUserFromDb();
  const dto = new UserDTO(user);
  res.json(dto); // sends only needed fields
});
DTO limits data to essential fields, reducing payload size and serialization time.
📈 Performance GainPayload size reduced by up to 50%, faster JSON serialization, improves LCP
Sending user data in an API response
Express
app.get('/user', (req, res) => {
  const user = getUserFromDb();
  res.json(user); // sends entire user object including sensitive and unnecessary fields
});
Sending the full user object increases payload size and exposes sensitive data.
📉 Performance CostIncreases payload size by 20-50%, blocks rendering longer due to larger JSON parsing
Performance Comparison
PatternDOM OperationsReflowsPaint CostVerdict
Sending full data objectN/AN/AHigh due to large JSON parsing[X] Bad
Sending DTO with minimal fieldsN/AN/ALow due to smaller JSON parsing[OK] Good
Rendering Pipeline
Data sent from server is serialized to JSON, transferred over network, parsed by browser, and rendered. Smaller payloads speed up parsing and rendering.
Network Transfer
JSON Parsing
Rendering
⚠️ BottleneckNetwork Transfer and JSON Parsing due to large payloads
Core Web Vital Affected
LCP
This pattern affects how data is prepared and sent over the network, impacting response size and serialization time.
Optimization Tips
1Always send only necessary data in API responses to reduce payload size.
2Use DTOs to control and limit data fields sent to clients.
3Smaller JSON payloads improve network transfer and parsing speed, enhancing LCP.
Performance Quiz - 3 Questions
Test your performance knowledge
How does using a DTO pattern affect API response performance?
AIncreases payload size by adding extra fields
BReduces payload size and speeds up JSON parsing
CHas no effect on performance
DBlocks rendering by adding more DOM nodes
DevTools: Network
How to check: Open DevTools > Network tab, reload the API call, inspect the response payload size and content.
What to look for: Look for smaller JSON response size and faster load times indicating efficient data transfer.