Skip to main content

Simple Express Server with StatusFlow

This example shows how to create a basic Express API with StatusFlow error handling.
1

Install Dependencies

First, install the required packages:
npm install express status-flow
npm install -D @types/express typescript
2

Create Basic Server

Create a simple Express server with StatusFlow:
import express from 'express';
import { StatusFlow, StatusFlowCodes, statusFlowMiddleware } from 'status-flow';

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

// Success endpoint using StatusFlow function
app.get('/api/status', (req, res) => {
  res.json(
    StatusFlow({
      code: StatusFlowCodes.OK,
      extra: { 
        server: 'online',
        timestamp: new Date().toISOString()
      }
    })
  );
});

// User endpoint with validation
app.get('/api/users/:id', (req, res, next) => {
  const userId = req.params.id;
  
  // Simulate validation error
  if (!userId || userId === '0') {
    return next({
      code: StatusFlowCodes.BAD_REQUEST,
      message: 'Invalid user ID',
      extra: { field: 'id' }
    });
  }
  
  // Simulate user not found
  if (userId === '999') {
    return next({
      code: StatusFlowCodes.NOT_FOUND,
      message: 'User not found',
      extra: { userId }
    });
  }
  
  // Return success response
  res.json(
    StatusFlow({
      code: StatusFlowCodes.OK,
      extra: {
        user: {
          id: userId,
          name: 'John Doe',
          email: 'john@example.com'
        }
      }
    })
  );
});

// Error handling middleware (must be last)
app.use(statusFlowMiddleware);

const PORT = 3000;
app.listen(PORT, () => {
  console.log(`Server running on http://localhost:${PORT}`);
});
3

Run the Server

Start your server:
# TypeScript
npx tsx server.ts

# JavaScript
node server.js
4

Test the Endpoints

Test your API endpoints using curl:
curl http://localhost:3000/api/status

Example Responses

{
  "success": true,
  "message": "HTTP 200 - Correcto",
  "code": 200,
  "server": "online",
  "timestamp": "2026-03-07T10:30:00.000Z",
  "info": {
    "name": "Correcto",
    "category": "Respuesta exitosa",
    "description": "La solicitud se completó exitosamente",
    "possibleCauses": [
      "Operación completada correctamente"
    ]
  }
}
{
  "success": false,
  "message": "Invalid user ID",
  "code": 400,
  "field": "id",
  "info": {
    "name": "Solicitud incorrecta",
    "category": "Error del cliente",
    "description": "La solicitud no pudo ser procesada debido a errores de sintaxis",
    "possibleCauses": [
      "Parámetros faltantes o inválidos",
      "Formato de datos incorrecto"
    ]
  }
}
{
  "success": false,
  "message": "User not found",
  "code": 404,
  "userId": "999",
  "info": {
    "name": "No encontrado",
    "category": "Error del cliente",
    "description": "El recurso solicitado no existe",
    "possibleCauses": [
      "URL incorrecta",
      "Recurso eliminado o movido"
    ]
  }
}

Using HTTP Exceptions

StatusFlow also provides HTTP exception classes for cleaner error handling:
import { 
  BadRequestException, 
  NotFoundException,
  httpErrorMiddleware 
} from 'status-flow';

// Throw exceptions directly
app.get('/api/products/:id', (req, res) => {
  if (!req.params.id) {
    throw new BadRequestException('Product ID is required');
  }
  
  const product = findProduct(req.params.id);
  if (!product) {
    throw new NotFoundException('Product not found');
  }
  
  res.json(product);
});

// Use the httpErrorMiddleware instead
app.use(httpErrorMiddleware);
The statusFlowMiddleware provides bilingual responses with rich metadata, while httpErrorMiddleware provides simpler responses. Choose based on your needs.

Key Concepts

StatusFlow Function

Use the StatusFlow() function to create standardized responses with custom data in the extra field.

StatusFlowCodes

Use constants like StatusFlowCodes.OK instead of magic numbers for better code readability.

Middleware

Always add error handling middleware last, after all your routes are defined.

Extra Data

Add any custom data to your responses using the extra parameter.
Start with the StatusFlow function for simple use cases. Move to HTTP exceptions when you need more control over error handling.

Next Steps

Advanced Integration

Learn advanced patterns for production applications

Bilingual API

Create APIs that support multiple languages

Build docs developers (and LLMs) love