edge-master
v0.10.0
Published
A Micro Framework for Edges
Maintainers
Readme
The Edge Complexity Problem
As edge applications grow, managing complexity becomes critical. What starts as a simple Worker with a few routes quickly becomes an unmaintainable mess of if-else statements, scattered middleware, and duplicated logic. EdgeMaster solves this by providing a structured, scalable architecture specifically designed for edge computing.
Why EdgeMaster?
EdgeMaster is a lightweight microframework purpose-built for edge environments like Cloudflare Workers, AWS Lambda@Edge, and other serverless platforms. It brings structure to chaos by providing:
- 🎯 Structured Routing - HTTP method helpers, grouping, and priority-based matching
- 🔄 Interceptor Pattern - Middleware for request/response transformation
- 📦 Task-Based Architecture - Reusable, composable units of work
- ⚡ Zero Dependencies - No bloat, minimal bundle size (~14 KB)
- 🛡️ Production Ready - Built-in auth, rate limiting, caching, and error handling
- 💎 Type Safe - Full TypeScript support with strict typing
Quick Start
Installation
npm install edge-masterHello World
import { EdgeController, RouteHandler, Task, json } from 'edge-master';
const app = new EdgeController();
app.GET('/hello', new RouteHandler(new Task({
do: async () => json({ message: 'Hello World!' })
})));
export default {
fetch: (req: Request) => app.handleRequest({ req })
};That's it! You've built a working edge application.
Core Features
🎯 HTTP Method Helpers
Clean, expressive routing with built-in method helpers:
app.GET('/users', listHandler);
app.POST('/users', createHandler);
app.PUT('/users/:id', updateHandler);
app.DELETE('/users/:id', deleteHandler);📦 Route Grouping
Organize routes hierarchically:
app.group('/api/v1', (v1) => {
v1.group('/users', (users) => {
users.GET('/', listUsers);
users.GET('/:id', getUser);
users.POST('/', createUser);
});
});🔄 Powerful Interceptors
Apply cross-cutting concerns with middleware:
import { corsInterceptor, jwtInterceptor, rateLimitInterceptor } from 'edge-master';
// CORS
app.addInterceptor(corsInterceptor({ origin: '*' }));
// Authentication
app.addInterceptor(jwtInterceptor({
verify: (token) => verifyJWT(token, env.JWT_SECRET),
exclude: ['/auth/*', '/public/*']
}));
// Rate Limiting
app.addInterceptor(rateLimitInterceptor({
limit: 100,
window: 60000,
storage: new KVRateLimitStorage(env.KV)
}));📝 Request & Response Helpers
Convenient utilities for common operations:
import { parseJSON, json, badRequest, notFound } from 'edge-master';
app.POST('/users', new RouteHandler(new Task({
do: async ({ req }) => {
const body = await parseJSON(req);
if (!body.email || !body.name) {
return badRequest('Email and name are required');
}
const user = await createUser(body);
return json({ user }, { status: 201 });
}
})));🎭 Context State Management
Share data between interceptors and handlers:
import { setState, getState } from 'edge-master';
// In interceptor
app.addInterceptor({
type: InterceptorType.Request,
async intercept(ctx) {
setState(ctx, 'user', await authenticateUser(ctx.reqCtx.req));
return ctx.reqCtx.req;
}
});
// In handler
app.GET('/profile', new RouteHandler(new Task({
do: async (ctx) => {
const user = getState(ctx, 'user');
return json({ user });
}
})));Real-World Example
Here's a complete REST API with authentication, validation, and error handling:
import {
EdgeController,
RouteHandler,
Task,
json,
parseJSON,
corsInterceptor,
jwtInterceptor,
getState,
badRequest,
notFound,
unauthorized
} from 'edge-master';
const app = new EdgeController();
// Add interceptors
app.addInterceptor(corsInterceptor({ origin: '*' }));
app.addInterceptor(jwtInterceptor({
verify: (token) => verifyJWT(token, env.JWT_SECRET),
exclude: ['/auth/*']
}));
// Public routes
app.POST('/auth/login', new RouteHandler(new Task({
do: async ({ req }) => {
const { email, password } = await parseJSON(req);
const token = await generateToken(email, password);
if (!token) {
return unauthorized('Invalid credentials');
}
return json({ token });
}
})));
// Protected routes
app.GET('/users', new RouteHandler(new Task({
do: async () => {
const users = await getUsers();
return json({ users });
}
})));
app.POST('/users', new RouteHandler(new Task({
do: async ({ req }) => {
const body = await parseJSON(req);
if (!body.email || !body.name) {
return badRequest('Email and name are required');
}
const user = await createUser(body);
return json({ user }, { status: 201 });
}
})));
app.GET('/users/:id', new RouteHandler(new Task({
do: async ({ req }) => {
const id = new URL(req.url).pathname.split('/').pop();
const user = await getUser(id);
if (!user) {
return notFound(`User ${id} not found`);
}
return json({ user });
}
})));
// Export
export default {
fetch: (request: Request, env: any) => app.handleRequest({ req: request, env })
};Built-in Interceptors
EdgeMaster includes production-ready interceptors:
🔒 Authentication
- JWT Interceptor - Token verification with exclude patterns
- API Key Interceptor - API key validation
🚦 Rate Limiting
- Memory or KV-backed storage
- Per-IP or custom key generation
- Configurable limits and windows
📝 Logging
- Request/response logging
- Configurable log levels
- Timing information
🔄 CORS
- Full CORS support
- Configurable origins, methods, headers
- Automatic OPTIONS handling
⚡ Caching
- Cloudflare Cache API integration
- Configurable TTL and cache keys
- Vary header support
Documentation
- Getting Started - Build your first app
- Core Concepts - Understand the architecture
- API Reference - Complete API docs
- Examples - Real-world examples
- Best Practices - Recommended patterns
- Performance Optimization - Optimize your app
- Troubleshooting - Debug common issues
Examples & Use Cases
We provide 10 comprehensive examples covering common patterns:
- API Gateway - Complete REST API with CRUD operations
- JWT Authentication - Full auth system with RBAC
- Caching Strategies - Edge caching patterns
- Microservices Proxy - Service routing
- Security - Rate limiting & validation
- A/B Testing - Feature flags
- Image Optimization - Image transformation
- Workers KV - KV storage integration
- Workers AI - AI integration
- RPC Bindings - Service-to-service communication
Why Choose EdgeMaster?
vs Express.js
- ✅ Purpose-built for edge environments
- ✅ Zero dependencies vs many
- ✅ ~14 KB bundle vs ~200 KB
- ✅ <1ms cold starts vs slower
vs Hono
- ✅ Task-based architecture for complexity management
- ✅ Built-in production features (auth, rate limiting, caching)
- ✅ Context state management
- ✅ Priority routing
vs itty-router
- ✅ Structured architecture for large applications
- ✅ Rich feature set out of the box
- ✅ Enterprise-ready interceptors
- ✅ Comprehensive TypeScript types
Roadmap & Future Enhancements
We're continuously improving EdgeMaster. Here's what's on our radar:
Planned Features
- OpenAPI 3.0 specification generation from routes
- GraphQL adapter for edge
- WebSocket support for Durable Objects
- Built-in observability (tracing, metrics)
- Enhanced D1 database helpers
- R2 storage utilities
- Queue and Pub/Sub integrations
- AI/ML helper utilities
- Edge-native testing framework
- CLI tool for scaffolding projects
Improvements
- Enhanced TypeScript inference
- Performance optimizations
- More built-in interceptors
- Additional example applications
- Video tutorials and guides
Want to suggest a feature? Open an issue or email us!
Contributing
We welcome contributions from the community! EdgeMaster is built by developers, for developers.
How to Contribute
- Fork the repository on GitHub
- Install dependencies:
npm install - Run tests:
npm run test(ensure they pass) - Make your changes with tests
- Commit and push to your fork
- Submit a pull request with a clear description
What We're Looking For
- 🐛 Bug fixes
- ✨ New features (discuss in an issue first)
- 📝 Documentation improvements
- 🧪 Additional test coverage
- 💡 Example applications
- 🎨 Performance optimizations
Development Setup
# Clone your fork
git clone https://github.com/YOUR_USERNAME/edge-master.git
cd edge-master
# Install dependencies
npm install
# Run tests
npm test
# Build
npm run buildGuidelines
- Maintain backward compatibility
- Follow existing code style
- Write tests for new features
- Update documentation as needed
- Keep commits focused and clear
Community & Support
Get Help
- 📚 Documentation - Comprehensive guides and API reference
- 💬 GitHub Discussions - Ask questions and share ideas
- 🐛 GitHub Issues - Report bugs and request features
- 📧 Email: [email protected] - Direct support
Stay Updated
- ⭐ Star on GitHub - Show your support
- 👀 Watch Releases - Get notified of new versions
- 🐦 Follow updates on social media
Credits & Acknowledgments
EdgeMaster is developed and maintained by Sharif Eiri.
Philosophy
EdgeMaster is inspired by the simplicity and elegance of microframeworks like Express.js, but purpose-built for the unique constraints and opportunities of edge computing. Our mission is to bring structure and scalability to edge applications without sacrificing performance.
Special Thanks
- The Cloudflare Workers team for building an amazing platform
- The open-source community for inspiration and contributions
- All contributors who have helped improve EdgeMaster
License
EdgeMaster is MIT licensed. See the LICENSE file for details.
