Skip to main content

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:

MiddlewareDescription
CORSCross-origin resource sharing
Body ParserJSON and URL-encoded body parsing
Rate LimitRequest rate limiting per IP
Request IDAdds a unique ID to each request
LoggerLogs each request with timing
Error HandlerCatches 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

VariableDefaultDescription
PORT3000Server port
CORS_ORIGIN*Allowed origins (comma-separated)
CORS_CREDENTIALSfalseAllow credentials
RATE_LIMIT_MAX100Max requests per window
RATE_LIMIT_WINDOW60000Window duration in ms
BODY_LIMIT10mbMaximum request body size