Consumers of your API benefit enormously when every endpoint returns responses in a predictable shape. This lesson covers designing and enforcing a consistent JSON response format across an Express API.
Why Response Consistency Matters
Without a shared convention, different routes in the same API often return data in inconsistent shapes, sometimes a bare array, sometimes an object, sometimes a raw error string. This forces every client to write special-case handling for each endpoint.
A simple, consistent envelope, a top-level object with success, data, and error fields, lets client code handle every response the same way, whether it succeeded or failed.
Combine a consistent response format with a centralized error handler (from the Error Middleware lesson) so every unhandled error in the app, not just ones you explicitly catch, comes back in the same shape.
app.use((err, req, res, next) => {
const status = err.status || 500;
res.status(status).json({
success: false,
error: { message: status === 500 ? 'Internal server error' : err.message },
});
});
Common Mistakes
Returning a bare array from some endpoints and a wrapped object from others.
Sending different error shapes from different parts of the codebase.
Exposing internal error details or stack traces directly in the response body.
Forgetting pagination metadata on collection endpoints, forcing clients to guess.
Key Takeaways
A consistent JSON envelope, success, data, error, simplifies client-side handling.
Reusable response helper functions keep the shape consistent across every route.
Collection endpoints should include pagination metadata alongside the data array.
A centralized error handler ensures even unexpected errors match the same response shape.
Pro Tip
Document your response envelope shape once, in a shared README or API spec, and treat any endpoint that doesn't match it as a bug, consistency is far easier to maintain than to retrofit.
You now know how to design consistent API responses. Next, learn how Express handles incoming data in the Request Body lesson.