Introduction
LibreChat provides a comprehensive REST API built on Express.js that powers all client-server interactions. The API follows RESTful principles and supports multiple authentication methods for flexible integration.
Base URL Configuration
The API server can be configured through environment variables:
PORT=3080 # Default: 3080, use PORT=0 for automatic assignment
HOST=localhost # Default: localhost
DOMAIN_CLIENT=http://localhost:3090
DOMAIN_SERVER=http://localhost:3080
The default API base URL is:
http://localhost:3080/api
When HOST=0.0.0.0, the server listens on all network interfaces but should be accessed via http://localhost:{PORT}.
API Architecture
LibreChat’s API is organized into logical route groups:
Core Routes
| Route | Purpose | Authentication |
|---|
/api/auth | Authentication endpoints | Public/JWT |
/api/user | User management | JWT Required |
/api/messages | Message operations | JWT Required |
/api/convos | Conversation management | JWT Required |
/api/presets | Preset configurations | JWT Required |
/api/prompts | Prompt management | JWT Required |
Advanced Features
| Route | Purpose | Authentication |
|---|
/api/assistants | AI Assistants API | JWT Required |
/api/agents | Agent system | JWT Required |
/api/files | File upload/management | JWT Required |
/api/search | Search functionality | JWT Required |
/api/models | Model configuration | JWT Required |
/api/endpoints | Endpoint management | JWT Required |
Administration
| Route | Purpose | Authentication |
|---|
/api/admin | Admin operations | JWT + Admin Role |
/api/keys | API key management | JWT Required |
/api/api-keys | Agent API keys | JWT Required |
/api/roles | Role management | JWT Required |
/api/permissions | Access permissions | JWT Required |
/api/balance | Token balance | JWT Required |
Integration & Social
| Route | Purpose | Authentication |
|---|
/oauth | OAuth providers | Public |
/api/share | Share conversations | JWT Required |
/api/actions | Custom actions | JWT Required |
/api/mcp | MCP integration | JWT Required |
/api/memories | Memory management | JWT Required |
/api/tags | Tag system | JWT Required |
System Routes
// Health check endpoint
GET /health
// Returns: 200 OK
// Static image serving
GET /images/:path
// Requires: Valid image token or authentication
// API 404 handler
GET /api/*
// Returns: 404 for unmatched routes
Content Type
All API requests should use JSON:
Content-Type: application/json
Request Body Limits
app.use(express.json({ limit: '3mb' }));
app.use(express.urlencoded({ extended: true, limit: '3mb' }));
Requests exceeding 3MB will be rejected with a 413 Payload Too Large error.
Middleware Stack
The API employs several security and processing middleware:
Security Middleware
// MongoDB query sanitization
app.use(mongoSanitize());
// CORS support
app.use(cors());
// Cookie parsing
app.use(cookieParser());
// Trust proxy headers
app.set('trust proxy', 1);
Compression
Response compression is enabled by default:
DISABLE_COMPRESSION=false # Set to true to disable
Error Handling
The API uses a centralized error controller:
// Error handler (must be last middleware)
app.use(ErrorController);
Standard Error Response
{
"message": "Error description",
"code": "ERROR_CODE",
"status": 400
}
Common HTTP Status Codes
| Code | Meaning | Usage |
|---|
200 | Success | Request completed successfully |
201 | Created | Resource created successfully |
400 | Bad Request | Invalid request parameters |
401 | Unauthorized | Missing or invalid authentication |
403 | Forbidden | Insufficient permissions |
404 | Not Found | Resource not found |
422 | Unprocessable Entity | Validation failed |
429 | Too Many Requests | Rate limit exceeded |
500 | Internal Server Error | Server-side error |
Rate Limiting
LibreChat implements rate limiting on sensitive endpoints:
// Login endpoint
router.post('/login', middleware.loginLimiter, ...);
// Registration endpoint
router.post('/register', middleware.registerLimiter, ...);
// Password reset
router.post('/requestPasswordReset', middleware.resetPasswordLimiter, ...);
Rate limits help protect against brute force attacks and abuse. Limits vary by endpoint type.
CORS Configuration
CORS is enabled for cross-origin requests:
For production deployments, configure CORS appropriately:
DOMAIN_CLIENT=https://your-client-domain.com
DOMAIN_SERVER=https://your-api-domain.com
Sub-Directory Deployment
LibreChat supports serving the application from a sub-directory:
if (process.env.DOMAIN_CLIENT) {
const clientUrl = new URL(process.env.DOMAIN_CLIENT);
const baseHref = clientUrl.pathname.endsWith('/')
? clientUrl.pathname
: `${clientUrl.pathname}/`;
// Updates base href in index.html
}
Set DOMAIN_CLIENT=https://yourdomain.com/chat to serve from the /chat path.
Database Connection
The API connects to MongoDB on startup:
await connectDb();
logger.info('Connected to MongoDB');
// Background index synchronization
indexSync().catch((err) => {
logger.error('[indexSync] Background sync failed:', err);
});
Startup Sequence
The server initialization follows this sequence:
- Database Connection - Connect to MongoDB
- Database Seeding - Initialize required collections
- Configuration Loading - Load app configuration
- File Storage - Initialize file storage system
- Startup Checks - Validate system requirements
- Permissions - Update interface permissions
- Middleware Setup - Configure Express middleware
- Authentication - Initialize Passport strategies
- Routes Registration - Mount API routes
- Server Start - Listen on configured port
- Post-Startup Tasks - Initialize MCP, OAuth managers, migrations
Environment Variables
Key environment variables for API configuration:
# Server Configuration
PORT=3080
HOST=localhost
TRUST_PROXY=1
# Domains
DOMAIN_CLIENT=http://localhost:3090
DOMAIN_SERVER=http://localhost:3080
# Features
ALLOW_SOCIAL_LOGIN=true
DISABLE_COMPRESSION=false
CONTINUE_ON_UNCAUGHT_EXCEPTION=false
# Authentication
JWT_SECRET=your-secret-key
JWT_REFRESH_SECRET=your-refresh-secret
SESSION_EXPIRY=900000 # 15 minutes in ms
REFRESH_TOKEN_EXPIRY=604800000 # 7 days in ms
# Email
ALLOW_UNVERIFIED_EMAIL_LOGIN=false
# Monitoring
MEM_DIAG=false
Next Steps