HTTP Server
The HTTP module provides an Express-based HTTP server with built-in middleware for CORS, rate limiting, body parsing, and request logging.
Usage
import { FluxKit } from "@fluxkitdev/core";
const app = new FluxKit({
database: { uri: process.env.MONGODB_URI },
server: {
cors: {
origin: ["http://localhost:5173"],
credentials: true,
},
rateLimit: {
windowMs: 60_000,
max: 100,
},
},
});
// Add custom routes
app.http.get("/hello", (req, res) => {
res.json({ message: "Hello from FluxKit!" });
});
app.http.post("/echo", (req, res) => {
res.json({ received: req.body });
});
await app.start({ port: 3000 });
API Reference
app.http.get(path, handler)
Register a GET route.
app.http.post(path, handler)
Register a POST route.
app.http.put(path, handler)
Register a PUT route.
app.http.delete(path, handler)
Register a DELETE route.
app.http.use(middleware)
Register a middleware function.
app.http.use((req, res, next) => {
req.startTime = Date.now();
next();
});
Route with Validation
import { Schema } from "@fluxkitdev/core";
app.http.post("/users", {
body: Schema.object({
email: Schema.string().email().required(),
name: Schema.string().min(2).required(),
}),
handler: async (req, res) => {
// req.body is validated and typed
const user = await createUser(req.body);
res.status(201).json(user);
},
});
Route with Authentication
app.http.get("/profile", {
auth: true, // requires valid JWT
handler: async (req, res) => {
// req.user is available
res.json(req.user);
},
});
Built-in Middleware
The following middleware is applied automatically:
| Middleware | Description |
|---|---|
| CORS | Cross-origin resource sharing |
| Body Parser | JSON and URL-encoded body parsing |
| Rate Limit | Request rate limiting per IP |
| Request ID | Adds a unique ID to each request |
| Logger | Logs each request with timing |
| Error Handler | Catches errors and returns structured JSON |
Custom Error Handling
import { HttpError } from "@fluxkitdev/core";
app.http.get("/protected", async (req, res) => {
if (!req.headers.authorization) {
throw new HttpError(401, "UNAUTHORIZED", "Authentication required");
}
// ...
});
Error responses follow a standard format:
{
"error": {
"code": "UNAUTHORIZED",
"message": "Authentication required"
}
}
Configuration
| Variable | Default | Description |
|---|---|---|
PORT | 3000 | Server port |
CORS_ORIGIN | * | Allowed origins (comma-separated) |
CORS_CREDENTIALS | false | Allow credentials |
RATE_LIMIT_MAX | 100 | Max requests per window |
RATE_LIMIT_WINDOW | 60000 | Window duration in ms |
BODY_LIMIT | 10mb | Maximum request body size |