Skip to main content

Overview

The StatusFlow function is the heart of the library. It takes an HTTP status code and returns a rich, structured response object with bilingual support, metadata, and customization options.

How It Works

StatusFlow uses a comprehensive JSON catalog (http-statuses.json) that contains information about all standard HTTP status codes. For each code, the catalog stores:
  • Status code and name (in English and Spanish)
  • Category (Informational, Success, Redirection, Client Error, Server Error)
  • Description and possible causes
  • Default response structure
  • Customization options
When you call StatusFlow, it looks up the status code in this catalog and builds a response object in your chosen language.

Function Signature

function StatusFlow(options: StatusFlowOptions): object

StatusFlowOptions Interface

The function accepts an options object with the following properties:
code
number
required
The HTTP status code (e.g., 200, 404, 500)
lang
'es' | 'en'
default:"'es'"
The language for the response. Supports Spanish (‘es’) and English (‘en’)
extra
Record<string, any>
default:"{}"
Additional custom fields to include in the response object
overrideMessage
string
Custom message to replace the default message for the status code

Return Structure

StatusFlow returns an object with the following structure:
{
  success: boolean,      // true for 2xx/3xx, false for 4xx/5xx
  message: string,       // Human-readable message in selected language
  code: number,          // HTTP status code
  info: {
    name: string,               // Status name (e.g., "Not Found")
    category: string,           // Category (e.g., "Client Error")
    description: string,        // Detailed description
    possibleCauses: string[]    // Array of possible causes
  },
  ...extra               // Any additional fields from 'extra' parameter
}

Basic Usage

import { StatusFlow } from 'status-flow';

// Get a 200 OK response in Spanish
const response = StatusFlow({ code: 200 });

console.log(response);
// {
//   success: true,
//   message: "HTTP 200 - Correcto",
//   code: 200,
//   info: {
//     name: "Correcto",
//     category: "Éxito",
//     description: "Código HTTP estándar de éxito 200.",
//     possibleCauses: ["Causa general dependiendo del contexto."]
//   }
// }

Advanced Usage

Custom Messages

Override the default message with your own:
const response = StatusFlow({
  code: 400,
  lang: 'en',
  overrideMessage: 'Invalid email format provided'
});

console.log(response.message);
// "Invalid email format provided"

Extra Fields

Add custom data to the response:
const response = StatusFlow({
  code: 201,
  lang: 'en',
  extra: {
    userId: '12345',
    timestamp: new Date().toISOString(),
    resource: '/api/users'
  }
});

console.log(response);
// {
//   success: true,
//   message: "HTTP 201 - Created",
//   code: 201,
//   userId: "12345",
//   timestamp: "2026-03-07T10:30:00.000Z",
//   resource: "/api/users",
//   info: { ... }
// }

Combining Options

Use all options together for complete customization:
const response = StatusFlow({
  code: 409,
  lang: 'es',
  overrideMessage: 'El usuario ya existe en el sistema',
  extra: {
    conflictField: 'email',
    existingId: '67890'
  }
});

StatusFlowCodes Constants

The library exports a StatusFlowCodes object containing named constants for all HTTP status codes. This provides type-safe, readable code instead of magic numbers.
import { StatusFlow, StatusFlowCodes } from 'status-flow';

// Instead of using magic numbers
const response1 = StatusFlow({ code: 404 });

// Use named constants for better readability
const response2 = StatusFlow({ code: StatusFlowCodes.NOT_FOUND });
const response3 = StatusFlow({ code: StatusFlowCodes.INTERNAL_SERVER_ERROR });
const response4 = StatusFlow({ code: StatusFlowCodes.CREATED });

Available Constants

All standard HTTP status codes are available as UPPER_SNAKE_CASE constants:
StatusFlowCodes.OK                        // 200
StatusFlowCodes.CREATED                   // 201
StatusFlowCodes.NO_CONTENT                // 204
StatusFlowCodes.BAD_REQUEST               // 400
StatusFlowCodes.UNAUTHORIZED              // 401
StatusFlowCodes.FORBIDDEN                 // 403
StatusFlowCodes.NOT_FOUND                 // 404
StatusFlowCodes.CONFLICT                  // 409
StatusFlowCodes.INTERNAL_SERVER_ERROR     // 500
// ... and many more

The HTTP Status Catalog

StatusFlow’s power comes from its comprehensive http-statuses.json catalog. Each entry contains:
{
  "404": {
    "code": 404,
    "name": {
      "en": "Not Found",
      "es": "No Encontrado"
    },
    "category": {
      "en": "Client Error",
      "es": "Error del Cliente"
    },
    "description": {
      "en": "Standard HTTP client error code 404.",
      "es": "Código HTTP estándar de error del cliente 404."
    },
    "possibleCauses": {
      "en": ["General cause depending on context."],
      "es": ["Causa general dependiendo del contexto."]
    },
    "defaultResponse": {
      "en": {
        "success": false,
        "message": "HTTP 404 - Not Found",
        "code": 404
      },
      "es": {
        "success": false,
        "message": "HTTP 404 - No Encontrado",
        "code": 404
      }
    },
    "userCustomizable": {
      "extra": {}
    }
  }
}
The catalog includes all standard HTTP status codes from 100-599, covering informational, success, redirection, client error, and server error responses.

Unknown Status Codes

If you provide a status code that doesn’t exist in the catalog, StatusFlow returns a fallback error response:
const response = StatusFlow({ code: 9999 });

console.log(response);
// {
//   success: false,
//   message: "Código HTTP desconocido: 9999",
//   code: 9999
// }
Always use standard HTTP status codes (100-599) to ensure proper responses with full metadata.

Type Definitions

// Language type
type StatusFlowLang = 'es' | 'en';

// Options interface
interface StatusFlowOptions {
  code: number;
  lang?: StatusFlowLang;
  extra?: Record<string, any>;
  overrideMessage?: string;
}

// Internal catalog structure
type StatusJson = {
  [code: string]: {
    code: number;
    name: { en: string; es: string };
    category: { en: string; es: string };
    description: { en: string; es: string };
    possibleCauses: { en: string[]; es: string[] };
    defaultResponse: { en: any; es: any };
    userCustomizable: { extra: Record<string, any> };
  };
};

Best Practices

Use Named Constants

Prefer StatusFlowCodes.NOT_FOUND over magic numbers like 404

Respect Language Preference

Read the client’s language preference from headers or settings

Include Context

Use the extra field to provide additional context about errors

Custom Messages

Override messages when the default isn’t specific enough for your use case

Next Steps

HTTP Exceptions

Learn about exception classes for cleaner error handling

Bilingual Responses

Deep dive into the bilingual response system

Build docs developers (and LLMs) love