@tezx/test
Version:
File-based HTTP router for Node, Bun, and Deno with support for dynamic routes, middleware, static files, and WebSocket — built for TezX.
257 lines (193 loc) • 8.08 kB
Markdown
# @tezx/router
> A high-performance, file-based routing framework for Node.js, Deno, and Bun, with built-in middleware, WebSocket, SSE, static file serving, and devtools support — all TypeScript-first.
## Table of Contents
- [@tezx/router](#tezxrouter)
- [Table of Contents](#table-of-contents)
- [Introduction](#introduction)
- [Installation](#installation)
- [Project Structure](#project-structure)
- [Routing Conventions](#routing-conventions)
- [Middleware System](#middleware-system)
- [File-based per-route middleware \& handlers](#file-based-per-route-middleware--handlers)
- [Global Middleware](#global-middleware)
- [Middleware Signature](#middleware-signature)
- [WebSocket \& SSE Support](#websocket--sse-support)
- [Static File Serving](#static-file-serving)
- [Configuration](#configuration)
- [Example `tezx.config.mjs`](#example-tezxconfigmjs)
- [Development \& Build Workflow](#development--build-workflow)
- [API Reference](#api-reference)
- [Advanced Usage](#advanced-usage)
- [FAQ](#faq)
- [Contributing](#contributing)
## Introduction
**@tezx/router** is a versatile, runtime-agnostic routing framework built on top of [TezX core](https://npmjs.com/package/tezx). It enables seamless file-system routing with support for dynamic and optional route parameters, middleware per method and route, WebSocket & SSE handlers, static file serving, and more — all configurable for Node.js, Deno, and Bun environments.
Key features:
- File-based routing supporting dynamic (`[id]`), optional (`[[slug]]`), and catch-all (`[...path]`) segments
- Middleware support per HTTP method, route, and globally
- WebSocket (`_WS`) and Server-Sent Events (`_SSE`) support
- Static assets served from `routes/static` or configured external directories
- TypeScript-first with multi-target build outputs (CJS, ESM, types)
- Environment adapters for Node, Deno, and Bun
- Integrated devtools for route inspection and debugging
## Installation
```bash
npm install tezx @tezx/router
# or
yarn add tezx @tezx/router
```
## Project Structure
```text
my-app/
├── routes/ # Route handler files & middleware
│ ├── index.ts # GET /
│ ├── about.ts # GET /about
│ ├── contact.ts # GET /contact
│ ├── blog/
│ │ ├── [slug].ts # GET /blog/:slug
│ │ └── create.ts # POST /blog/create
│ ├── _middleware.ts # Global middleware (all routes)
│ ├── 404.ts # Not found handler
│ ├── 500.ts # Error handler
│ ├── static/
│ │ └── hello.txt # Static files served at /static/hello.txt
├── public/ # Optional static asset folder
│ └── favicon.ico # Served at /favicon.ico
├── server.ts # Application entry point
├── package.json
└── tsconfig.json
```
## Routing Conventions
- **Static routes:** `about.ts` → `/about`
- **Dynamic routes:** `[id].ts` → `/123` (required param)
- **Optional routes:** `[[slug]].ts` → `/` or `/hello` (optional param)
- **Catch-all routes:** `[...path].ts` → `/a/b/c` (wildcard param)
Filenames map to paths automatically: `[param]` → `:param`, `[[param]]` → optional, `[...param]` → wildcard.
Supported HTTP methods:
`GET`, `POST`, `PUT`, `DELETE`, `PATCH`, `OPTIONS`, and `SSE` (Server-Sent Events).
## Middleware System
### File-based per-route middleware & handlers
| Export Name | Purpose |
| ------------- | ------------------------------------------ |
| `_MIDDLEWARE` | Middleware applied for all HTTP methods |
| `_GET` | Handler or middleware for GET requests |
| `_POST` | Handler or middleware for POST requests |
| `_PUT` | Handler or middleware for PUT requests |
| `_DELETE` | Handler or middleware for DELETE requests |
| `_PATCH` | Handler or middleware for PATCH requests |
| `_OPTIONS` | Handler or middleware for OPTIONS requests |
| `_SSE` | Handler/middleware for Server-Sent Events |
| `_WS` | WebSocket handler or middleware |
### Global Middleware
Place `_middleware.ts` inside `routes/` folder to apply middleware globally.
### Middleware Signature
```ts
import type { Context, Next } from "tezx";
export async function _MIDDLEWARE(ctx: Context, next: Next) {
console.log(`[${ctx.method}] ${ctx.path}`);
await next();
}
```
## WebSocket & SSE Support
- Export `_WS` for WebSocket handlers/middleware (coexists with HTTP handlers).
- Export `_SSE` for Server-Sent Events with middleware signature.
**Example WebSocket Handler:**
```ts
export const _WS = (ctx,next) => {
};
```
## Static File Serving
- Place static assets inside `routes/static/` to serve under `/static` prefix.
- Configure external static directories (e.g., `public/`) via `staticDir` in config.
- Supported formats: `.html`, `.json`, `.txt`, images, fonts, etc.
## Configuration
### Example `tezx.config.mjs`
```js
/** @type {import('@tezx/router').TezxConfig} */
export default {
debugMode: true,
environment: "node", // 'node' | 'deno' | 'bun'
PORT: 3000,
compileTo: "js" ,
routesDir: "./routes",
staticDir: "./public",
enableStatic: true,
enableLogger: true,
buildOptions: [
{
name: "cjs",
module: "CommonJS",
target: "ES2017",
outDir: "dist/cjs",
removeComments: true,
},
{
name: "esm",
module: "ESNext",
target: "ES2020",
outDir: "dist/esm",
removeComments: true,
},
{
name: "types",
module: "ESNext",
outDir: "dist/types",
declaration: true,
emitDeclarationOnly: true,
},
],
devtools: {
path: "/devtools",
handler: require("@tezx/devtools").default,
},
};
```
## Development & Build Workflow
```bash
tezx-router dev # Start development server with watch mode
tezx-router build # Compile and generate route manifest
tezx-router start # Start production server
```
## API Reference
- `loadRoutesFromFolder(app: TezX, dir: string, options?)` — Auto-loads route files, middlewares, WebSocket, SSE handlers, static files.
- `TezX` constructor options:
- `basePath`: string — Prefix all routes
- `debugMode`: boolean — Logs route loading details
- `env`: object — Environment variables
- `allowDuplicateMw`: boolean — Allow multiple middlewares with same name
- `onPathResolve`: (routePath: string) => string — Customize route path resolving
- `overwriteMethod`: (ctx: Context) => string — Override HTTP method detection
## Advanced Usage
- Use `_MIDDLEWARE` to secure routes or perform preprocessing like auth, logging.
- Combine WebSocket `_WS` with HTTP handlers for real-time + REST hybrid endpoints.
- Leverage devtools for route inspection, live reload, and debugging.
- Customize build outputs with `buildOptions` for CJS, ESM, and type declarations.
- Serve static assets from multiple folders via `staticDir` config.
## FAQ
**Q: Can I use `@tezx/router` with Express or other frameworks?**
A: It's designed to work standalone with TezX core and its adapters for Node, Deno, and Bun.
**Q: How do I define global middleware?**
A: Create a `_middleware.ts` in the `routes/` folder exporting `_MIDDLEWARE`.
**Q: How do I serve static files outside the routes folder?**
A: Set `staticDir` in config (e.g., `"public"`) and enable `enableStatic`.
**Q: How do I handle 404 and error pages?**
A: Add `404.ts` and `500.ts` in your routes folder for custom handling.
**Q: What environments does this support?**
A: Official support for Node.js, Deno, and Bun with environment adapters.
## Contributing
We welcome contributions! Please open issues or PRs at [GitHub repository](https://github.com/tezxjs/tezx-router). Follow code style, write tests, and update docs.