SyntaxStudy
Sign Up
Node.js Response Format and Error Handling
Node.js Beginner 9 min read

Response Format and Error Handling

Consistent response shapes make your API predictable for clients. A common convention wraps all responses in a structure with data, error, and optional meta fields. Centralise error handling with a global Express error middleware.

Example
// utils/response.js — response helpers
function success(res, data, statusCode = 200, meta = null) {
    const body = { success: true, data };
    if (meta) body.meta = meta;
    return res.status(statusCode).json(body);
}

function fail(res, message, statusCode = 400, details = null) {
    const body = { success: false, error: { message } };
    if (details) body.error.details = details;
    return res.status(statusCode).json(body);
}

module.exports = { success, fail };

// Usage in a route:
// const { success, fail } = require('./utils/response');
// app.get('/users/:id', async (req, res, next) => {
//   try {
//     const user = await User.findById(req.params.id);
//     if (!user) return fail(res, 'User not found', 404);
//     return success(res, user);
//   } catch (err) {
//     next(err); // Pass to global error handler
//   }
// });

// Global error handler (app.js):
// app.use((err, req, res, next) => {
//   const status = err.statusCode || 500;
//   const msg    = err.message    || 'Internal Server Error';
//   res.status(status).json({ success: false, error: { message: msg } });
// });

// Response shapes:
// Success: { success: true, data: { id: 1, name: 'Alice' } }
// List:    { success: true, data: [...], meta: { total: 42, page: 1 } }
// Error:   { success: false, error: { message: 'Not found' } }