Skip to main content
StatusFlow provides utility functions for creating standardized HTTP responses in your Express applications.

createHttpResponse

Converts an HttpException instance into a structured HTTP response object.

Function Signature

function createHttpResponse(error: HttpException): HttpResponse

Parameters

error
HttpException
required
An instance of HttpException (or any class that extends it).

Return Type

interface HttpResponse {
  status: number;
  message: string;
  details?: unknown;
}
status
number
The HTTP status code from the exception.
message
string
The error message from the exception.
details
unknown
Additional details from the exception, if any were provided.

Examples

Basic Usage

import { createHttpResponse, NotFoundException } from 'status-flow';

const exception = new NotFoundException('User not found');
const response = createHttpResponse(exception);

console.log(response);
Output:
{
  "status": 404,
  "message": "User not found",
  "details": undefined
}

With Details

import { createHttpResponse, BadRequestException } from 'status-flow';

const exception = new BadRequestException('Validation failed', {
  errors: [
    { field: 'email', message: 'Invalid format' },
    { field: 'age', message: 'Must be positive' }
  ]
});

const response = createHttpResponse(exception);
console.log(response);
Output:
{
  "status": 400,
  "message": "Validation failed",
  "details": {
    "errors": [
      { "field": "email", "message": "Invalid format" },
      { "field": "age", "message": "Must be positive" }
    ]
  }
}

In Express Route

import express from 'express';
import { createHttpResponse, NotFoundException } from 'status-flow';

const app = express();

app.get('/users/:id', async (req, res) => {
  try {
    const user = await findUser(req.params.id);
    
    if (!user) {
      const exception = new NotFoundException('User not found', {
        userId: req.params.id
      });
      const response = createHttpResponse(exception);
      return res.status(response.status).json(response);
    }
    
    res.json({ success: true, data: user });
  } catch (error) {
    res.status(500).json({ success: false, message: 'Server error' });
  }
});

createSuccessResponse

Creates a standardized success response object with data.

Function Signature

function createSuccessResponse<T>(
  data: T,
  message?: string,
  status?: number
): HttpResponse & { data: T }

Parameters

data
T
required
The data to include in the response. Can be of any type.
message
string
default:"'OK'"
Optional success message.
status
number
default:"200"
Optional HTTP status code. Defaults to 200.

Return Type

interface SuccessResponse<T> extends HttpResponse {
  status: number;
  message: string;
  data: T;
}
status
number
The HTTP status code (default: 200).
message
string
The success message (default: “OK”).
data
T
The response data of type T.

Examples

Basic Usage

import { createSuccessResponse } from 'status-flow';

const user = { id: '123', name: 'John Doe', email: 'john@example.com' };
const response = createSuccessResponse(user);

console.log(response);
Output:
{
  "status": 200,
  "message": "OK",
  "data": {
    "id": "123",
    "name": "John Doe",
    "email": "john@example.com"
  }
}

With Custom Message

import { createSuccessResponse } from 'status-flow';

const user = { id: '123', name: 'John Doe' };
const response = createSuccessResponse(
  user,
  'User retrieved successfully'
);

console.log(response);
Output:
{
  "status": 200,
  "message": "User retrieved successfully",
  "data": {
    "id": "123",
    "name": "John Doe"
  }
}

With 201 Created Status

import { createSuccessResponse } from 'status-flow';

const newUser = { id: '456', name: 'Jane Doe' };
const response = createSuccessResponse(
  newUser,
  'User created successfully',
  201
);

console.log(response);
Output:
{
  "status": 201,
  "message": "User created successfully",
  "data": {
    "id": "456",
    "name": "Jane Doe"
  }
}

Array Data

import { createSuccessResponse } from 'status-flow';

const users = [
  { id: '1', name: 'John' },
  { id: '2', name: 'Jane' }
];

const response = createSuccessResponse(
  users,
  'Users retrieved successfully'
);

console.log(response);
Output:
{
  "status": 200,
  "message": "Users retrieved successfully",
  "data": [
    { "id": "1", "name": "John" },
    { "id": "2", "name": "Jane" }
  ]
}

HttpResponse Interface

The base interface for all response objects.
interface HttpResponse {
  status: number;
  message: string;
  details?: unknown;
}
status
number
The HTTP status code.
message
string
A human-readable message.
details
unknown
Optional additional details. Can be any type.

Complete Express Example

import express from 'express';
import { 
  createSuccessResponse,
  createHttpResponse,
  NotFoundException,
  BadRequestException
} from 'status-flow';

const app = express();
app.use(express.json());

// GET endpoint with success response
app.get('/users/:id', async (req, res) => {
  try {
    const user = await userService.findById(req.params.id);
    
    if (!user) {
      const exception = new NotFoundException('User not found');
      const response = createHttpResponse(exception);
      return res.status(response.status).json(response);
    }
    
    const response = createSuccessResponse(user, 'User found');
    res.status(response.status).json(response);
  } catch (error) {
    res.status(500).json({ status: 500, message: 'Server error' });
  }
});

// POST endpoint with 201 response
app.post('/users', async (req, res) => {
  try {
    const { email, name } = req.body;
    
    if (!email || !name) {
      const exception = new BadRequestException(
        'Email and name are required'
      );
      const response = createHttpResponse(exception);
      return res.status(response.status).json(response);
    }
    
    const newUser = await userService.create({ email, name });
    const response = createSuccessResponse(
      newUser,
      'User created successfully',
      201
    );
    
    res.status(response.status).json(response);
  } catch (error) {
    res.status(500).json({ status: 500, message: 'Server error' });
  }
});

app.listen(3000);

Type Safety with TypeScript

Both functions provide full TypeScript support:
import { createSuccessResponse } from 'status-flow';

interface User {
  id: string;
  name: string;
  email: string;
}

// Type parameter ensures data matches User interface
const response = createSuccessResponse<User>({
  id: '123',
  name: 'John Doe',
  email: 'john@example.com'
});

// response.data is typed as User
console.log(response.data.email); // Type-safe

Best Practices

1. Use Appropriate Status Codes

// 200 for successful GET
createSuccessResponse(users, 'Users retrieved');

// 201 for successful POST
createSuccessResponse(newUser, 'User created', 201);

// 204 for successful DELETE (no content)
res.status(204).send();

2. Provide Meaningful Messages

// ✅ Good
createSuccessResponse(user, 'User retrieved successfully');

// ❌ Not helpful
createSuccessResponse(user, 'OK');

3. Include Details in Error Responses

const exception = new BadRequestException('Validation failed', {
  fields: {
    email: 'Invalid format',
    password: 'Too short'
  }
});

const response = createHttpResponse(exception);

4. Combine with Middleware

import { httpErrorMiddleware } from 'status-flow';

// Manual response creation in routes
app.get('/users/:id', async (req, res) => {
  const response = createSuccessResponse(user);
  res.json(response);
});

// Automatic error handling with middleware
app.use(httpErrorMiddleware);

Build docs developers (and LLMs) love