Overview
One of StatusFlow’s key features is built-in support for bilingual responses. Every HTTP status code in the library has both Spanish (es) and English (en) translations, allowing you to serve international users with responses in their preferred language.
Supported Languages
StatusFlow currently supports two languages:
Spanish (es) Default language - Comprehensive translations for all HTTP status codes
English (en) Full English support for international applications
Spanish (es) is the default language when no language is specified. This can be changed by always providing the lang parameter.
How Language Selection Works
1. Explicit Language Parameter
The most direct way to specify a language is through the lang parameter:
import { StatusFlow } from 'status-flow' ;
// Spanish response (default)
const spanishResponse = StatusFlow ({ code: 404 });
console . log ( spanishResponse . message );
// "HTTP 404 - No Encontrado"
// English response
const englishResponse = StatusFlow ({ code: 404 , lang: 'en' });
console . log ( englishResponse . message );
// "HTTP 404 - Not Found"
In Express middleware, StatusFlow can automatically detect language from the x-lang header:
import { statusFlowMiddleware } from 'status-flow' ;
import express from 'express' ;
const app = express ();
// Middleware automatically reads x-lang header
app . use ( statusFlowMiddleware );
// Client request with header:
// x-lang: en
//
// Response will be in English
The middleware checks the x-lang header:
If x-lang: en, responses are in English
Otherwise (or if missing), responses default to Spanish
3. Custom Language Detection
You can implement custom language detection based on your application’s needs:
import { StatusFlow , type StatusFlowLang } from 'status-flow' ;
function getClientLanguage ( req : Request ) : StatusFlowLang {
// Option 1: Custom header
const customHeader = req . headers [ 'x-language' ];
if ( customHeader === 'en' || customHeader === 'es' ) {
return customHeader ;
}
// Option 2: Accept-Language header
const acceptLanguage = req . headers [ 'accept-language' ];
if ( acceptLanguage ?. includes ( 'es' )) return 'es' ;
if ( acceptLanguage ?. includes ( 'en' )) return 'en' ;
// Option 3: Query parameter
const langQuery = req . query . lang ;
if ( langQuery === 'en' || langQuery === 'es' ) {
return langQuery ;
}
// Option 4: User settings from database
if ( req . user ?. preferredLanguage ) {
return req . user . preferredLanguage ;
}
// Default to Spanish
return 'es' ;
}
app . get ( '/data' , ( req , res ) => {
const lang = getClientLanguage ( req );
const response = StatusFlow ({
code: 200 ,
lang ,
extra: { data: someData }
});
res . json ( response );
});
Response Structure by Language
Every response field is translated based on the selected language:
Spanish (es)
English (en)
const response = StatusFlow ({ code: 404 , lang: 'es' });
console . log ( response );
// {
// success: false,
// message: "HTTP 404 - No Encontrado",
// code: 404,
// info: {
// name: "No Encontrado",
// category: "Error del Cliente",
// description: "Código HTTP estándar de error del cliente 404.",
// possibleCauses: ["Causa general dependiendo del contexto."]
// }
// }
const response = StatusFlow ({ code: 404 , lang: 'en' });
console . log ( response );
// {
// success: false,
// message: "HTTP 404 - Not Found",
// code: 404,
// info: {
// name: "Not Found",
// category: "Client Error",
// description: "Standard HTTP client error code 404.",
// possibleCauses: ["General cause depending on context."]
// }
// }
Translated Fields
The following fields are translated:
Field Spanish Example English Example message”HTTP 404 - No Encontrado" "HTTP 404 - Not Found” info.name”No Encontrado" "Not Found” info.category”Error del Cliente" "Client Error” info.description”Código HTTP estándar de error del cliente 404." "Standard HTTP client error code 404.” info.possibleCauses[“Causa general dependiendo del contexto.”] [“General cause depending on context.”]
Common Status Code Translations
Here’s a reference of commonly used status codes in both languages:
Success Responses (2xx)
StatusFlow ({ code: 200 , lang: 'es' })
// "HTTP 200 - Correcto"
StatusFlow ({ code: 201 , lang: 'es' })
// "HTTP 201 - Creado"
StatusFlow ({ code: 204 , lang: 'es' })
// "HTTP 204 - Sin Contenido"
StatusFlow ({ code: 200 , lang: 'en' })
// "HTTP 200 - OK"
StatusFlow ({ code: 201 , lang: 'en' })
// "HTTP 201 - Created"
StatusFlow ({ code: 204 , lang: 'en' })
// "HTTP 204 - No Content"
Client Errors (4xx)
StatusFlow ({ code: 400 , lang: 'es' })
// "HTTP 400 - Solicitud Incorrecta"
StatusFlow ({ code: 401 , lang: 'es' })
// "HTTP 401 - No Autorizado"
StatusFlow ({ code: 403 , lang: 'es' })
// "HTTP 403 - Prohibido"
StatusFlow ({ code: 404 , lang: 'es' })
// "HTTP 404 - No Encontrado"
StatusFlow ({ code: 409 , lang: 'es' })
// "HTTP 409 - Conflicto"
StatusFlow ({ code: 400 , lang: 'en' })
// "HTTP 400 - Bad Request"
StatusFlow ({ code: 401 , lang: 'en' })
// "HTTP 401 - Unauthorized"
StatusFlow ({ code: 403 , lang: 'en' })
// "HTTP 403 - Forbidden"
StatusFlow ({ code: 404 , lang: 'en' })
// "HTTP 404 - Not Found"
StatusFlow ({ code: 409 , lang: 'en' })
// "HTTP 409 - Conflict"
Server Errors (5xx)
StatusFlow ({ code: 500 , lang: 'es' })
// "HTTP 500 - Error Interno del Servidor"
StatusFlow ({ code: 502 , lang: 'es' })
// "HTTP 502 - Puerta de Enlace Incorrecta"
StatusFlow ({ code: 503 , lang: 'es' })
// "HTTP 503 - Servicio No Disponible"
StatusFlow ({ code: 500 , lang: 'en' })
// "HTTP 500 - Internal Server Error"
StatusFlow ({ code: 502 , lang: 'en' })
// "HTTP 502 - Bad Gateway"
StatusFlow ({ code: 503 , lang: 'en' })
// "HTTP 503 - Service Unavailable"
Message Customization
While StatusFlow provides default translations, you can override messages in any language using the overrideMessage parameter:
// Override Spanish default
const spanishCustom = StatusFlow ({
code: 404 ,
lang: 'es' ,
overrideMessage: 'El usuario no fue encontrado en el sistema'
});
console . log ( spanishCustom . message );
// "El usuario no fue encontrado en el sistema"
// Override English default
const englishCustom = StatusFlow ({
code: 404 ,
lang: 'en' ,
overrideMessage: 'The requested user was not found in our database'
});
console . log ( englishCustom . message );
// "The requested user was not found in our database"
When you override a message, only the message field is changed. The info object retains the default translations for that language.
Practical Examples
Multi-language API Endpoint
import express from 'express' ;
import { StatusFlow , type StatusFlowLang } from 'status-flow' ;
const app = express ();
// Language detection middleware
app . use (( req , res , next ) => {
const lang = req . headers [ 'x-lang' ] === 'en' ? 'en' : 'es' ;
req . lang = lang as StatusFlowLang ;
next ();
});
// API endpoint that respects language preference
app . get ( '/api/users/:id' , async ( req , res ) => {
try {
const user = await findUser ( req . params . id );
if ( ! user ) {
const response = StatusFlow ({
code: 404 ,
lang: req . lang ,
overrideMessage: req . lang === 'es'
? 'Usuario no encontrado'
: 'User not found'
});
return res . status ( 404 ). json ( response );
}
const response = StatusFlow ({
code: 200 ,
lang: req . lang ,
extra: { user }
});
res . json ( response );
} catch ( error ) {
const response = StatusFlow ({
code: 500 ,
lang: req . lang ,
overrideMessage: req . lang === 'es'
? 'Error al procesar la solicitud'
: 'Error processing request'
});
res . status ( 500 ). json ( response );
}
});
StatusFlow Middleware with Language Detection
import { Request , Response , NextFunction } from 'express' ;
import { StatusFlow } from 'status-flow' ;
function statusFlowMiddleware (
err : any ,
req : Request ,
res : Response ,
_next : NextFunction
) {
// Detect language from header (en or default to es)
const lang = req . headers [ 'x-lang' ] === 'en' ? 'en' : 'es' ;
if ( err && typeof err . code === 'number' ) {
// Handle errors with status codes
const response = StatusFlow ({
code: err . code ,
lang ,
extra: err . extra || {},
overrideMessage: err . message || undefined ,
});
res . status ( err . code ). json ( response );
} else {
// Handle unknown errors
const response = StatusFlow ({
code: 500 ,
lang ,
overrideMessage: lang === 'es'
? 'Error interno del servidor'
: 'Internal server error' ,
extra: { originalError: err },
});
res . status ( 500 ). json ( response );
}
}
Building a Language Helper
Create a helper to standardize language handling across your app:
import { StatusFlow , type StatusFlowLang } from 'status-flow' ;
import { Request } from 'express' ;
class ResponseHelper {
static getLanguage ( req : Request ) : StatusFlowLang {
// Check custom header
if ( req . headers [ 'x-lang' ] === 'en' ) return 'en' ;
// Check user preferences
if ( req . user ?. language === 'en' ) return 'en' ;
// Default to Spanish
return 'es' ;
}
static success ( req : Request , data : any , code = 200 ) {
const lang = this . getLanguage ( req );
return StatusFlow ({
code ,
lang ,
extra: { data }
});
}
static error ( req : Request , code : number , message ?: string ) {
const lang = this . getLanguage ( req );
return StatusFlow ({
code ,
lang ,
overrideMessage: message
});
}
}
// Usage in routes
app . get ( '/api/products' , async ( req , res ) => {
const products = await getProducts ();
res . json ( ResponseHelper . success ( req , products ));
});
app . get ( '/api/products/:id' , async ( req , res ) => {
const product = await getProduct ( req . params . id );
if ( ! product ) {
const lang = ResponseHelper . getLanguage ( req );
const message = lang === 'es'
? 'Producto no encontrado'
: 'Product not found' ;
return res . status ( 404 ). json ( ResponseHelper . error ( req , 404 , message ));
}
res . json ( ResponseHelper . success ( req , product ));
});
Best Practices
Consistent Language Detection
Use a consistent method for detecting language across your entire application. Don’t mix multiple approaches randomly.
Default Language Strategy
Choose a default language based on your primary user base. StatusFlow defaults to Spanish, but you can always specify English if that better suits your needs.
Custom Message Translations
When using overrideMessage, provide translations for both languages to maintain consistency: const message = lang === 'es'
? 'Credenciales inválidas'
: 'Invalid credentials' ;
StatusFlow ({ code: 401 , lang , overrideMessage: message });
Document Language Support
Clearly document in your API documentation which languages are supported and how clients should specify their preference.
Type Safety
StatusFlow provides type-safe language handling:
import { type StatusFlowLang } from 'status-flow' ;
// Correct usage
const validLang : StatusFlowLang = 'es' ; // ✓
const validLang2 : StatusFlowLang = 'en' ; // ✓
// TypeScript error - invalid language
const invalidLang : StatusFlowLang = 'fr' ; // ✗ TypeScript error
This prevents typos and ensures only supported languages are used:
// Safe with autocomplete
function createResponse ( lang : StatusFlowLang ) {
return StatusFlow ({ code: 200 , lang }); // TypeScript knows lang is valid
}
Future Language Support
StatusFlow currently supports Spanish and English. Additional languages may be added in future versions. Check the GitHub repository for updates and feature requests.
If you need support for additional languages, consider:
Opening an issue on the GitHub repository
Contributing translations via pull request
Implementing a custom translation layer on top of StatusFlow
Next Steps
StatusFlow Function Master the core StatusFlow function
HTTP Exceptions Learn about exception-based error handling