0
0
NextJSframework~8 mins

Response formatting in NextJS - Performance & Optimization

Choose your learning style9 modes available
Performance: Response formatting
MEDIUM IMPACT
Response formatting affects how quickly the server sends data and how efficiently the browser processes it, impacting page load speed and interaction readiness.
Sending JSON data from a Next.js API route
NextJS
export default function handler(req, res) {
  const data = { message: 'Hello World', time: new Date().toISOString() };
  res.json(data);
}
Using res.json automatically sets headers and stringifies data efficiently; formatting date as ISO string reduces payload size.
📈 Performance GainSaves CPU cycles on manual stringify; smaller payload reduces network latency.
Sending JSON data from a Next.js API route
NextJS
export default function handler(req, res) {
  const data = { message: 'Hello World', time: new Date() };
  res.setHeader('Content-Type', 'application/json');
  res.send(JSON.stringify(data));
}
Manually stringifying JSON and setting headers can cause redundant processing and potential errors; also, sending unnecessary data increases payload size.
📉 Performance CostAdds extra CPU time for manual JSON.stringify; larger payload increases network transfer time.
Performance Comparison
PatternDOM OperationsReflowsPaint CostVerdict
Manual JSON.stringify with extra dataN/A0Low but delayed by parsing[X] Bad
res.json with minimal dataN/A0Low and fast parsing[OK] Good
Rendering Pipeline
Response formatting affects the server-to-browser data transfer stage and the browser's parsing stage, influencing how quickly content becomes available for rendering.
Network Transfer
HTML/JSON Parsing
Rendering
⚠️ BottleneckNetwork Transfer and Parsing
Core Web Vital Affected
LCP
Response formatting affects how quickly the server sends data and how efficiently the browser processes it, impacting page load speed and interaction readiness.
Optimization Tips
1Use res.json() to send JSON responses efficiently.
2Minimize data sent in responses to reduce payload size.
3Avoid manual JSON.stringify and header setting to save CPU time.
Performance Quiz - 3 Questions
Test your performance knowledge
Which response formatting method in Next.js improves performance by reducing CPU usage and payload size?
AUsing res.json() with minimal data
BManually stringifying JSON and setting headers
CSending data as plain text without headers
DSending large objects with unnecessary fields
DevTools: Network
How to check: Open DevTools, go to Network tab, reload the page or API call, select the response, and inspect the payload size and content.
What to look for: Look for smaller payload size and correct Content-Type header indicating efficient response formatting.