### Install FalconFrame with bun add
Source: https://github.com/wxn0brp/falconframe/blob/master/README.md
Install the FalconFrame library using the Bun package manager.
```bash
bun add @wxn0brp/falcon-frame
```
--------------------------------
### FalconFrame usage example with routes, middleware, and validation
Source: https://github.com/wxn0brp/falconframe/blob/master/README.md
Complete usage example for FalconFrame: sets CORS origin, global and auth middleware, static file serving, login/register/logout routes with validation and cookies, a protected dashboard route, a 404 handler, and starts the server on port 3000.
```ts
import FalconFrame, { validateBody } from "@wxn0brp/falcon-frame";
const app = new FalconFrame();
app.setOrigin("*");
const USERS = {
admin: "hunter2",
};
// Global middleware
app.use((req, res, next) => {
console.log(`[${req.method}] ${req.path}`);
next();
});
// Middleware: auth check
const requireAuth = (req, res, next) => {
if (req.cookies.session === "admin") {
return next();
}
res.status(401).json({ error: "Unauthorized" });
};
// Static files
app.static("/", "public");
app.post("/login", (req, res) => {
const { valid, validErrors } = req.valid({
username: "required|string",
password: "required|string",
});
if (!valid) {
return res.status(400).json({ status: "error", errors: validErrors });
}
const { username, password } = req.body;
if (USERS[username] === password) {
res.cookie("session", username, { httpOnly: true });
return res.redirect("/dashboard");
}
res.status(401).json({ status: "fail", message: "Invalid credentials" });
});
app.post(
"/register",
validateBody({
username: "required|string|min:3|max:20",
password: "required|string|min:8",
}),
(req, res) => {
const { username, password } = req.body;
USERS[username] = password;
return { status: "success", message: "User registered successfully" };
}
);
// Protected route
app.get("/dashboard", requireAuth, (req, res) => {
return {
message: `Welcome to the dashboard, ${req.cookies.session}`,
});
});
app.post("/logout", (req, res) => {
res.cookie("session", "", { maxAge: 0 });
res.json({ message: "Logged out" });
});
// if no route matches
app.set404((req, res) => {
res.status(404).json({ error: "Not found" });
});
// Start the server (env.PORT || 3000)
app.l(3000);
```
--------------------------------
### Internal Template Data Example
Source: https://github.com/wxn0brp/falconframe/blob/master/docs/render.md
Demonstrates how a content template can set the
for its parent layout using an HTML comment with JSON data. The setup shows that no data needs to be passed via JavaScript for the title.
```html
{{ title }}
{{ body }}
```
```html
Welcome!
This is the home page content.
```
```javascript
// Assuming app.setVar("layout", "layouts/main.html") has been called
app.render("pages/home.html");
// No data needs to be passed via JS for the title
```
```html
My Awesome Home Page
Welcome!
This is the home page content.
```
--------------------------------
### Partial Inclusion Example
Source: https://github.com/wxn0brp/falconframe/blob/master/docs/render.md
Demonstrates partial inclusion: the main template includes a partial file via a comment directive, and the partial is rendered with data. The result shows the combined output.
```html
```
```html
```
```javascript
const data = { username: "JaneDoe" };
```
```html
```
--------------------------------
### Layout Handling Example
Source: https://github.com/wxn0brp/falconframe/blob/master/docs/render.md
Shows how to set a layout and render a template within it. The layout uses {{ title }} and {{ body }} placeholders, and the template content is inserted into the layout's body. The result shows the full rendered page.
```javascript
app.setVar("layout", "layouts/main.html");
```
```html
{{ title }}
{{ body }}
```
```html
About Us
This is the about page content.
```
```javascript
const data = { title: "My Awesome Site" };
```
```html
My Awesome Site
About Us
This is the about page content.
```
--------------------------------
### Example error response
Source: https://github.com/wxn0brp/falconframe/blob/master/docs/valid.md
Example error response showing the structure of validation errors.
```typescript
{
valid: false,
validErrors: {
email: ["email must be a valid email"],
age: ["age must be at least 18"]
}
}
```
--------------------------------
### Data Interpolation Example
Source: https://github.com/wxn0brp/falconframe/blob/master/docs/render.md
Shows how to interpolate a variable into an HTML template. The template uses {{ name }} placeholders, the data object provides the value, and the result shows the rendered output.
```html
Hello, {{ name }}!
Welcome to our site.
```
```javascript
const data = { name: "Alex" };
```
```html
Hello, Alex!
Welcome to our site.
```
--------------------------------
### POST /profile
Source: https://github.com/wxn0brp/falconframe/blob/master/docs/valid.md
Example of using validateBody middleware with custom regex validation for profile fields.
```APIDOC
## [POST] /profile
### Description
Validates the request body with custom regex patterns for specific fields.
### Method
POST
### Endpoint
/profile
### Parameters
#### Request Body
- **website** (string) - Optional - Must match the regex pattern /^https?:\/\/.+/
- **phone** (string) - Required - Must match the regex pattern ^\+?[0-9]{9,15}$
### Request Example
{
"website": "https://example.com",
"phone": "+1234567890"
}
### Response
#### Success Response (200)
- **success** (boolean) - Indicates the validation passed.
#### Response Example
{
"success": true
}
#### Error Response (400)
Returns a 400 status with error details if validation fails.
```
--------------------------------
### POST /register
Source: https://github.com/wxn0brp/falconframe/blob/master/docs/valid.md
Example of using validateBody middleware to validate a registration request body.
```APIDOC
## [POST] /register
### Description
Validates the request body against the provided validation rules before passing to the route handler.
### Method
POST
### Endpoint
/register
### Parameters
#### Request Body
- **email** (string) - Required - Must be a valid email address.
- **password** (string) - Required - Must be a string with a minimum length of 8 characters.
### Request Example
{
"email": "user@example.com",
"password": "password123"
}
### Response
#### Success Response (200)
- **success** (boolean) - Indicates the validation passed.
#### Response Example
{
"success": true
}
#### Error Response (400)
Returns a 400 status with error details if validation fails.
```
--------------------------------
### Raw File Inclusion Example
Source: https://github.com/wxn0brp/falconframe/blob/master/docs/render.md
Shows raw file inclusion: CSS and JavaScript files are included via comment directives in the HTML. The result shows the final HTML with the included content inlined.
```html
My Page
Welcome!
```
```css
body {
font-family: sans-serif;
color: #333;
}
```
```javascript
console.log("Page loaded successfully!");
```
```html
My Page
Welcome!
```
--------------------------------
### Optional fields with optional rule
Source: https://github.com/wxn0brp/falconframe/blob/master/docs/valid.md
Fields marked with optional, nullable, or opt skip all validation rules when the value is null or undefined. The example shows the expected outcomes for each call.
```typescript
const schema = {
email: "optional|email"
};
validate(schema, { email: null }); // Valid
validate(schema, { email: undefined }); // Valid
validate(schema, { email: "invalid" }); // Invalid - email format error
validate(schema, { email: "valid@example.com" }); // Valid
```
--------------------------------
### Schema format with pipe-separated rules
Source: https://github.com/wxn0brp/falconframe/blob/master/docs/valid.md
Schema format: keys are field names, values are pipe-separated rule strings. Parameters are passed using the : separator.
```typescript
const schema = {
fieldName: "rule1|rule2:param|rule3"
};
```
--------------------------------
### Product Validation Schema
Source: https://github.com/wxn0brp/falconframe/blob/master/docs/valid.md
Defines a validation schema for product data, including required fields, numeric constraints, allowed categories, and optional array/string limits.
```typescript
const schema = {
name: "required|string|max:100",
price: "required|number|min:0",
category: "required|in:electronics,clothing,books,other",
tags: "optional|array|max:5",
description: "optional|string|max:1000"
};
```
--------------------------------
### User Registration Schema
Source: https://github.com/wxn0brp/falconframe/blob/master/docs/valid.md
Defines a validation schema for user registration, enforcing required fields, string length, email format, password confirmation, and age range.
```typescript
const schema = {
username: "required|string|min:3|max:20",
email: "required|email",
password: "required|string|min:8",
confirmPassword: "required|same:password",
age: "required|number|min:18|max:120"
};
```
--------------------------------
### Profile Update Schema with Regex Rules
Source: https://github.com/wxn0brp/falconframe/blob/master/docs/valid.md
Defines a validation schema for profile updates with optional fields, and passes a custom regex rule for the website field to the validate function.
```typescript
const schema = {
email: "optional|email",
bio: "optional|string|max:500",
website: "optional|string",
social: "optional|object"
};
const regexRules = {
website: /^https?:\/\/.+/
};
validate(schema, data, regexRules);
```
--------------------------------
### Basic validation with validate()
Source: https://github.com/wxn0brp/falconframe/blob/master/docs/valid.md
Basic usage of the validate function with a schema and data object. The result has a valid boolean and validErrors array when validation fails.
```typescript
import { validate } from "@wxn0brp/falcon-frame";
const schema = {
email: "required|email",
age: "required|number|min:18",
username: "required|string|min:3|max:20"
};
const data = {
email: "user@example.com",
age: 25,
username: "john_doe"
};
const result = validate(schema, data);
if (result.valid) {
console.log("Validation passed");
} else {
console.log("Validation errors:", result.validErrors);
}
```
--------------------------------
### validate Return Value
Source: https://github.com/wxn0brp/falconframe/blob/master/docs/valid.md
Documentation of the return value of the validate function used by validateBody.
```APIDOC
## validate Function
### Description
Returns an object indicating whether validation passed and a map of field errors.
### Return Value
- **valid** (boolean) - Indicates if validation passed.
- **validErrors** (object) - An object mapping field names to arrays of error messages.
### Example Return
{
"valid": false,
"validErrors": {
"email": ["email must be a valid email"],
"age": ["age must be at least 18"]
}
}
```
--------------------------------
### Validate request body with validateBody
Source: https://github.com/wxn0brp/falconframe/blob/master/docs/valid.md
Use validateBody to validate request bodies in route handlers. The middleware automatically responds with a 400 status and error details if validation fails.
```typescript
import { validateBody } from "@wxn0brp/falcon-frame";
app.post("/register",
validateBody({
email: "required|email",
password: "required|string|min:8"
}),
(req, res) => {
// Validation passed, proceed with registration
res.json({ success: true });
}
);
```
--------------------------------
### Regex validation with regexRules parameter
Source: https://github.com/wxn0brp/falconframe/blob/master/docs/valid.md
Pass regex patterns as a separate parameter to avoid conflicts with the | and : separators. Both RegExp objects and string patterns are supported.
```typescript
const schema = {
website: "required|string",
code: "required|string"
};
const regexRules = {
website: /^https?:\/\/.+/,
code: "^[A-Z]{3}-[0-9]{4}$"
};
const result = validate(schema, data, regexRules);
```
--------------------------------
### Validate request body with regex patterns
Source: https://github.com/wxn0brp/falconframe/blob/master/docs/valid.md
Use validateBody with regex patterns for additional validation. The second argument provides regex patterns for specific fields.
```typescript
app.post("/profile",
validateBody(
{
website: "optional|string",
phone: "required|string"
},
{
website: /^https?:\/\/.+/,
phone: "^\\+?[0-9]{9,15}$"
}
),
(req, res) => {
res.json({ success: true });
}
);
```
--------------------------------
### API Request Validation Schema
Source: https://github.com/wxn0brp/falconframe/blob/master/docs/valid.md
Defines a validation schema for API requests, requiring an action from a set, an integer resource ID, and optional object/boolean fields.
```typescript
const schema = {
action: "required|in:create,update,delete",
resourceId: "required|integer",
metadata: "optional|object",
notify: "optional|boolean"
};
```
--------------------------------
### Return value of validate function
Source: https://github.com/wxn0brp/falconframe/blob/master/docs/valid.md
The validate function returns an object with a valid boolean and a validErrors object mapping field names to arrays of error messages.
```typescript
{
valid: boolean,
validErrors: {
[fieldName]: string[]
}
}
```