A robust, functional-style HTTP server built with Deno and Effection. This server implements secure static file serving, dynamic routing with RegExp support, comprehensive middleware system, and advanced structured concurrency patterns.
- Enhanced Static File Serving: Secure static file serving with path traversal protection and MIME type caching
- Advanced Dynamic Routing: Define routes with
path
(string or RegExp),method
, andhandler
- Comprehensive Middleware: Built-in middleware for logging, security headers, and request tracking
- Advanced Structured Concurrency: Leverages Effection for robust resource management and graceful shutdown
- Security Features: Strong security defaults with CSP and other security headers
- Request Tracking: Monitor and manage in-flight requests during shutdown
- Environment Configuration: Flexible configuration through environment variables
- Structured Logging: Detailed request logging with unique request IDs and timing
- Deno 1.37 or higher installed on your machine
- Understanding of TypeScript and async programming
-
Clone the repository:
git clone https://github.com/your-username/deno-http-server.git cd deno-http-server
-
Create a
public
directory for static files:mkdir public
-
Configure environment variables (optional):
export PORT=8000 export DENO_ENV=development export PUBLIC_DIR=./public export SHUTDOWN_TIMEOUT=5000
-
Start the server:
deno run --allow-net --allow-read --allow-env routes.ts
-
The server will start on
http://localhost:8000
(or configured PORT).
.
├── server/ # Server implementation
│ ├── server.ts # Main server implementation
│ └── deps.ts # Dependency management
├── routes.ts # Application routes
├── public/ # Directory for static files
│ ├── index.html # Example HTML file
│ ├── styles.css # Example CSS file
│ └── 404.html # Custom 404 error page
└── README.md # This file
Routes now support RegExp patterns and include Effection context:
// routes.ts
import { Route, serveStatic, start } from "../server/server.ts";
const routes: Route[] = [
{
path: "/",
method: "GET",
handler: async (req, context) => new Response("Hello, World!", { status: 200 }),
},
{
path: /^\/users\/(\d+)$/, // RegExp pattern for dynamic routes
method: "GET",
handler: async (req, context) => new Response("User details", { status: 200 }),
},
{
path: "/static",
method: "GET",
handler: async (req, context) => {
const url = new URL(req.url);
const filePath = `./public${url.pathname.substring("/static".length)}`;
return await serveStatic(filePath, context);
},
},
];
start(routes);
The server now includes enhanced middleware capabilities:
// Example custom middleware with context
const customMiddleware = (handler: RequestHandler): RequestHandler =>
async (req, context) => {
const response = await handler(req, context);
// Middleware logic here
return response;
};
// Built-in middleware includes:
// - Logging middleware with request tracking
// - Security headers middleware with configurable CSP
// - Request tracking middleware for graceful shutdown
Built-in security headers include:
{
"Content-Security-Policy": "default-src 'self'; script-src 'self' 'unsafe-inline'; style-src 'self' 'unsafe-inline';",
"X-Content-Type-Options": "nosniff",
"X-Frame-Options": "DENY",
"Strict-Transport-Security": "max-age=31536000; includeSubDomains",
"X-XSS-Protection": "1; mode=block"
}
Enhanced static file serving features:
- Path traversal protection
- Cached MIME type mapping
- Secure file access within public directory
- Proper error handling for missing files
const requestTracker = createRequestTracker();
// Tracks in-flight requests for graceful shutdown
yield* requestTracker.track(requestPromise);
The server now implements comprehensive shutdown handling:
- Captures SIGINT and SIGTERM signals
- Stops accepting new connections
- Waits for in-flight requests to complete (with timeout)
- Cleans up resources using Effection context
- Logs shutdown progress
Example log output:
{
"requestId": "uuid",
"method": "GET",
"url": "/path",
"status": 200,
"duration": 123,
"timestamp": "2024-12-30T12:00:00.000Z"
}
- Development mode: Detailed error messages
- Production mode: Generic error responses
- Proper error propagation through Effection context
- Comprehensive error logging
Same as before, plus:
-
Dynamic User Route:
curl http://localhost:8000/users/123
-
Additional Middleware:
- Request body parsing
- CORS support
- Rate limiting
-
Testing:
- Unit tests with Deno's testing framework
- Integration tests with request tracking
-
Monitoring:
- Metrics collection
- Health check endpoints
Contributions are welcome! Please open an issue or submit a pull request.
This project is licensed under the MIT License. See the LICENSE file for details.
- Built by DeepSeek & Cloude Sonet gently directed by yours truly.
- Built with Deno and Effection
- Inspired by functional programming principles and robust design patterns
🚀