
⚡ Qwe Framework
High-Performance, Zero-Dependency TypeScript Backend Framework
Built on uWebSockets.js • Express.js Alternative • Unified Context Pattern
🚀 npm install qwe-js
🏃 Quick Start • ✨ Features • 📚 Documentation • 💡 Examples • 🛠️ CLI Tools
✨ Features
🚀 Performance | 📝 Type Safety | 🛠️ Zero Dependencies |
---|---|---|
10x faster than Socket.IO 8.5x faster than Fastify |
Full TypeScript support Complete type definitions |
Built-in utilities No external packages |
🌟 Core Features
- ⚡ High Performance: Built on uWebSockets.js (10x faster than Socket.IO, 8.5x faster than Fastify)
- 🧠 Unified Context: Single
qwe
object replaces Express's(req, res)
pattern - 📘 TypeScript First: Full TypeScript support with comprehensive type definitions
- 🗄️ Multi-Database ORM: Built-in support for MongoDB, MySQL, PostgreSQL, SQLite, and SQL Server
- 🔒 Production Ready: Built-in security, validation, file upload capabilities
- 🔐 JWT Middleware: Built-in JWT authentication with role/permission-based access control
- 🔌 Plugin System: Extensible with
app.plugin(cors())
syntax - 🎯 Template Responses: Standardized API responses with
qwe.success()
,qwe.badRequest()
, etc. - 🛠️ CLI Tools: Project generator and module scaffolding
🤔 Why Choose Qwe?
💯 Developer Experience First
✨ What You Get | 🚀 Traditional Express | ⚡ Qwe Framework |
---|---|---|
Setup Time | Hours of configuration | Minutes with CLI |
Dependencies | 50+ packages | Zero external deps |
Type Safety | Manual setup required | Built-in TypeScript |
Validation | External libraries | Integrated validation |
Performance | Good | 10x faster |
Response Format | Manual standardization | Automatic templates |
Learning Curve | Steep | Gentle transition |
🏆 Perfect for Modern Development
✓ Microservices • ✓ APIs • ✓ Real-time Apps • ✓ Serverless • ✓ Enterprise
🏁 Performance Comparison
Framework | Requests/sec | Latency | Dependencies |
---|---|---|---|
Qwe ✨ | ~85,000 | ~1.2ms | 0 🎆 |
Express | ~8,500 | ~12ms | 50+ |
Fastify | ~10,000 | ~10ms | 20+ |
Koa | ~7,000 | ~15ms | 30+ |
Performance benchmarks may vary based on hardware and configuration
📚 Documentation
For comprehensive documentation, please visit our documentation directory:
Quick Start
- 📖 Full Documentation - Complete documentation overview
- 🚀 Installation Guide - Detailed installation instructions
- 🏗️ Core Architecture - Framework architecture and design
Feature Guides
- 🔌 Plugins System - Plugin development and usage
- 🛠️ Utilities - Built-in utility functions
- 🔐 Authentication - JWT and security features
- 🗄️ Database & ORM - Database integration and ORM
- ⚡ Real-time Features - WebSocket and SSE
Advanced Topics
- 🧪 Testing - Testing utilities and best practices
- 📊 Performance - Performance optimization
- 🚀 Deployment - Production deployment guide
- 📋 API Reference - Complete API documentation
📦 Installation
npm install qwe-js
For global CLI usage:
npm install -g qwe-js@alpha
Or create a new project:
npx create-qwe-js my-app
cd my-app
npm run dev
📄 Need help? Check our complete documentation for detailed guides and examples.
🏃 Quick Start
🚀 Get Started in 30 seconds!
# 📦 Install Qwe Framework
npm install qwe-js
# 🎨 Create a new project (optional)
npx create-qwe-js my-awesome-app
cd my-awesome-app
npm run dev
📝 Hello World Example
import { createApp, cors, logger } from 'qwe-js';
const app = createApp();
// 🔌 Add middleware
app.plugin(logger());
app.plugin(cors());
// 🌍 Define routes with unified context
app.get('/', (qwe) => {
qwe.success({
message: 'Hello World! 🌍',
framework: 'Qwe',
timestamp: new Date().toISOString()
});
});
app.post('/users', (qwe) => {
// ✅ Built-in validation
const validation = qwe.validate.object({
name: qwe.validate.string().min(2),
email: qwe.validate.string().email()
});
const result = validation.validate(qwe.body);
if (!result.success) {
return qwe.badRequest('Validation failed', result.errors);
}
// ✨ Create user with generated ID
const user = {
id: qwe.generateId(),
...result.data,
createdAt: new Date().toISOString()
};
qwe.created(user, 'User created successfully 🎉');
});
// 🚀 Start the server
app.listen(3000, () => {
console.log('🎆 Server running on http://localhost:3000');
});
🔑 Key Concepts
🧠 Unified Context Pattern
Express.js 🐌 | Qwe Framework ⚡ |
---|---|
(req, res) => {} |
(qwe) => {} |
2 objects to manage | 1 unified context |
Scattered functionality | Everything in one place |
// 🐌 Express Pattern - Multiple objects
app.get('/users', (req, res) => {
const body = req.body;
const query = req.query;
const params = req.params;
res.status(200).json({
users: [],
message: 'Users retrieved'
});
});
// ⚡ Qwe Pattern - Single unified context
app.get('/users', (qwe) => {
const { body, query, params } = qwe; // Everything in one place!
qwe.success({ users: [] }, 'Users retrieved'); // Template response!
});
🎯 Template Responses
Standardized, consistent API responses with built-in formatting:
app.post('/users', (qwe) => {
// ✅ Success responses
qwe.success(data, 'Success message'); // 200
qwe.created(data, 'Created successfully'); // 201
// ❌ Error responses
qwe.badRequest('Invalid input'); // 400
qwe.unauthorized('Access denied'); // 401
qwe.forbidden('Permission denied'); // 403
qwe.notFound('Resource not found'); // 404
qwe.conflict('Resource already exists'); // 409
qwe.unprocessableEntity('Validation failed'); // 422
qwe.internalServerError('Something went wrong'); // 500
});
All responses follow this consistent format:
{
"success": true,
"statusCode": 200,
"message": "Success message",
"data": { "id": "123", "name": "John" },
"timestamp": "2024-01-15T10:30:00.000Z",
"requestId": "req_7f8a9b2c3d4e5f6g"
}
🛠 Built-in Features
Validation
Zod-like validation engine:
app.post('/users', (qwe) => {
const schema = qwe.validate.object({
name: qwe.validate.string().min(2).max(50),
email: qwe.validate.string().email(),
age: qwe.validate.number().min(18).optional(),
tags: qwe.validate.array(qwe.validate.string())
});
const result = schema.validate(qwe.body);
if (!result.success) {
return qwe.unprocessableEntity('Validation failed', result.errors);
}
// Use validated data
const userData = result.data;
});
Authentication & Security
Built-in JWT and hashing:
app.post('/auth/login', async (qwe) => {
const { email, password } = qwe.body;
const user = await findUserByEmail(email);
const isValid = await qwe.hash.compare(password, user.password);
if (isValid) {
const token = qwe.jwt.sign(
{ userId: user.id, email },
'your-secret-key',
{ expiresIn: '24h' }
);
qwe.success({ token, user });
} else {
qwe.unauthorized('Invalid credentials');
}
});
// Password hashing
const hashedPassword = await qwe.hash.bcrypt('password123');
JWT Middleware
Qwe provides powerful JWT middleware for protecting routes:
Global Protection
import { createApp, jwtAuth } from 'qwe-js';
const app = createApp();
// Protect all routes globally
app.plugin(jwtAuth({ secret: 'your-jwt-secret' }));
// All routes after this middleware require JWT
app.get('/protected', (qwe) => {
const user = qwe.user; // Access authenticated user
qwe.success({ message: 'Protected data', user });
});
Route-Specific Protection
import { jwtMiddleware, requireRoles, requirePermissions } from 'qwe-js';
// Create middleware instance
const authMiddleware = jwtMiddleware({ secret: 'your-jwt-secret' });
// Protect individual routes
app.get('/profile', authMiddleware, (qwe) => {
qwe.success({ user: qwe.user });
});
// Role-based protection
app.get('/admin', authMiddleware, requireRoles('admin'), (qwe) => {
qwe.success({ message: 'Admin only content' });
});
// Permission-based protection
app.post('/write-data',
authMiddleware,
requirePermissions('write', 'admin'),
(qwe) => {
qwe.success({ message: 'Data written successfully' });
}
);
// Multiple roles
app.get('/staff', authMiddleware, requireRoles('admin', 'moderator'), (qwe) => {
qwe.success({ message: 'Staff area' });
});
Optional Authentication
import { optionalAuth } from 'qwe-js';
// Works with or without authentication
app.get('/public', optionalAuth({ secret: 'your-jwt-secret' }), (qwe) => {
const user = qwe.user; // null if not authenticated
qwe.success({
message: user ? 'Hello authenticated user!' : 'Hello guest!',
authenticated: !!user
});
});
Advanced JWT Configuration
const authMiddleware = jwtMiddleware({
secret: 'your-jwt-secret',
// Custom token extraction
getToken: (qwe) => {
// Extract from custom header
return qwe.headers['x-auth-token'] ||
qwe.query.token ||
qwe.cookies.token;
},
// Token revocation check
isRevoked: async (qwe, payload) => {
return await checkTokenRevocation(payload.jti);
},
// Custom error handling
onError: (qwe, error) => {
console.error('JWT Error:', error.message);
},
// Audience validation
audience: 'your-api',
// Issuer validation
issuer: 'your-app',
// Custom user property name
requestProperty: 'currentUser' // Access via qwe.currentUser
});
Ownership-Based Access Control
import { requireOwnershipOrRole } from 'qwe-js';
// Users can only access their own resources (or admins can access all)
app.get('/users/:id/profile',
authMiddleware,
requireOwnershipOrRole(
(qwe) => qwe.params.id, // Get resource owner ID
['admin', 'superuser'] // Admin roles that can access all
),
(qwe) => {
qwe.success({ profile: getUserProfile(qwe.params.id) });
}
);
JWT Token Structure
When using JWT middleware, include role and permission information in your tokens:
app.post('/auth/login', async (qwe) => {
// ... authentication logic ...
const token = qwe.jwt.sign({
userId: user.id,
email: user.email,
role: user.role, // For role-based access
permissions: user.permissions, // For permission-based access
// ... other claims
}, 'your-secret-key', {
expiresIn: '24h',
issuer: 'your-app',
audience: 'your-api'
});
qwe.success({ token, user });
});
File Uploads
Multer-like file handling:
app.post('/upload', (qwe) => {
const files = qwe.files; // Array of uploaded files
files.forEach(file => {
console.log(file.originalName, file.size, file.mimeType);
// Save file.buffer to storage
});
qwe.success({ uploaded: files.length });
});
Database & ORM
Built-in ORM with multi-database support:
// SQL Database (PostgreSQL, MySQL, SQLite)
const orm = createORM();
await orm.connect({
dialect: 'postgresql',
host: 'localhost',
port: 5432,
database: 'myapp',
username: 'user',
password: 'password'
});
// MongoDB
await orm.connect({
dialect: 'mongodb',
connectionString: 'mongodb://localhost:27017/myapp'
});
// Define models (works with all databases)
const User = orm.model('User', {
id: { type: 'string', primaryKey: true },
name: { type: 'string', required: true },
email: { type: 'string', required: true, unique: true },
profile: { type: 'json', default: {} }
});
app.post('/users', async (qwe) => {
const user = await User.create(qwe.body);
qwe.created(user, 'User created successfully');
});
app.get('/users', async (qwe) => {
const users = await User.findMany({
where: { active: true },
orderBy: { createdAt: 'desc' },
take: 10
});
qwe.success(users);
});
🔌 Plugin System
Built-in Plugins
import { createApp, cors, logger, rateLimiter, compression, security, jwtAuth } from 'qwe-js';
const app = createApp();
// CORS
app.plugin(cors({
origin: 'https://yourdomain.com',
credentials: true
}));
// Logging
app.plugin(logger({ format: 'combined' }));
// Rate limiting
app.plugin(rateLimiter({
max: 100,
windowMs: 60000
}));
// Compression
app.plugin(compression());
// Security headers
app.plugin(security({
contentSecurityPolicy: "default-src 'self'",
xFrameOptions: 'DENY'
}));
// JWT Authentication (global)
app.plugin(jwtAuth({
secret: 'your-jwt-secret',
credentialsRequired: true
}));
### Custom Plugins
```typescript
const customPlugin = {
name: 'my-plugin',
install: (app) => {
app.use(async (qwe, next) => {
qwe.header('X-Custom-Header', 'value');
await next();
});
}
};
app.plugin(customPlugin);
🏗 CLI Tools
Project Creation
# Create a new project
npx create-qwe-js my-project
# Or with global installation
npm install -g qwe-js@alpha
create-qwe-js my-project
Interactive setup with options:
- TypeScript/JavaScript
- ESLint & Prettier
- Testing framework
- Database integration
- Authentication
Module Generation
After installing globally:
# Install CLI globally
npm install -g qwe-js@alpha
# Generate traditional structure
qwe generate module user
# Generate NEW modular structure ✨
qwe generate modular-module auth
qwe generate modular-module product
qwe generate modular-module order
# Generate individual components
qwe generate controller product
qwe generate service email
qwe generate router api
qwe generate middleware auth
qwe generate models user
# Show help
qwe --help
Modular vs Traditional Structure
Traditional Structure (qwe generate module user
):
- Creates:
src/controllers/user.controller.ts
- Creates:
src/services/user.service.ts
- Creates:
src/routes/user.router.ts
Modular Structure (qwe generate modular-module user
) ✨:
- Creates:
src/modules/user/user.controller.ts
- Creates:
src/modules/user/user.service.ts
- Creates:
src/modules/user/user.routes.ts
- Creates:
src/modules/user/user.models.ts
🎆 New! The modular structure keeps related files together and includes models with TypeScript interfaces and DTOs.
📁 Project Structure
Standard Structure
my-qwe-app/
├── src/
│ ├── controllers/ # Route handlers (traditional structure)
│ ├── services/ # Business logic (traditional structure)
│ ├── routes/ # Route definitions (traditional structure)
│ ├── middleware/ # Custom middleware
│ ├── modules/ # Modular structure (NEW!)
│ │ ├── auth/ # Authentication module
│ │ │ ├── auth.controller.ts
│ │ │ ├── auth.service.ts
│ │ │ ├── auth.routes.ts
│ │ │ └── auth.models.ts
│ │ ├── user/ # User management module
│ │ │ ├── user.controller.ts
│ │ │ ├── user.service.ts
│ │ │ ├── user.routes.ts
│ │ │ └── user.models.ts
│ │ └── product/ # Product module
│ │ ├── product.controller.ts
│ │ ├── product.service.ts
│ │ ├── product.routes.ts
│ │ └── product.models.ts
│ ├── utils/ # Utility functions
│ ├── types/ # TypeScript type definitions
│ └── index.ts # Application entry point
├── tests/ # Test files
│ ├── unit/ # Unit tests
│ ├── integration/ # Integration tests
│ └── e2e/ # End-to-end tests
├── docs/ # Documentation
├── examples/ # Example applications
├── package.json
├── tsconfig.json
└── README.md
Generated Module Structure
With the new CLI generator, you can create modular structures:
# Generate modular structure
qwe generate modular-module auth
This creates a self-contained module:
src/modules/auth/
├── auth.controller.ts # CRUD operations (getAll, getById, create, update, delete)
├── auth.service.ts # Business logic with data management
├── auth.routes.ts # Route setup function with REST endpoints
└── auth.models.ts # TypeScript interfaces and DTOs
Module Benefits
- Self-contained: Each module has its own controller, service, routes, and models
- Type-safe: Full TypeScript support with interfaces and DTOs
- CRUD ready: Generated with complete CRUD operations
- Framework integrated: Uses Qwe's unified context pattern
- Easy to maintain: Clear separation of concerns within each module
🔧 Configuration
Environment Variables
# .env
PORT=3000
NODE_ENV=development
JWT_SECRET=your-super-secret-key
DATABASE_URL=your-database-url
LOG_LEVEL=info
TypeScript Configuration
{
"compilerOptions": {
"target": "ES2020",
"module": "commonjs",
"strict": true,
"esModuleInterop": true,
"skipLibCheck": true
}
}
🚀 Performance
Qwe is built on uWebSockets.js for maximum performance:
- 10x faster than Socket.IO
- 8.5x faster than Fastify
- 3x faster than Express.js
- Low memory footprint
- Zero external dependencies
📚 API Reference
QweContext Properties
interface QweContext {
// Request
body: any;
query: Record<string, string>;
params: Record<string, string>;
headers: Record<string, string>;
method: HttpMethod;
url: string;
ip: string;
cookies: Record<string, string>;
files: QweFile[];
// Response Methods
json(data: any): QweContext;
text(data: string): QweContext;
html(data: string): QweContext;
status(code: number): QweContext;
header(key: string, value: string): QweContext;
cookie(name: string, value: string, options?: CookieOptions): QweContext;
redirect(url: string, code?: number): QweContext;
// Template Responses
success(data?: any, message?: string, details?: any): QweContext;
created(data?: any, message?: string, details?: any): QweContext;
badRequest(message?: string, errors?: any, details?: any): QweContext;
unauthorized(message?: string, details?: any): QweContext;
forbidden(message?: string, details?: any): QweContext;
notFound(message?: string, details?: any): QweContext;
conflict(message?: string, details?: any): QweContext;
unprocessableEntity(message?: string, errors?: any, details?: any): QweContext;
internalServerError(message?: string, details?: any): QweContext;
// Built-in Utilities
validate: QweValidator;
hash: QweHasher;
jwt: QweJWT;
generateId(): string;
}
🧪 Testing
import { createApp } from 'qwe-js';
describe('User API', () => {
let app;
beforeEach(() => {
app = createApp();
});
test('should create user', async () => {
// Your test implementation
});
});
📋 Learn More
Complete Documentation
For comprehensive guides, tutorials, and detailed API references:
➡️ View Complete Documentation
Our documentation covers:
- Detailed installation and setup
- Architecture deep-dive
- Advanced features and plugins
- Performance optimization
- Production deployment
- Testing strategies
- Real-time features (WebSocket/SSE)
- Database integration and ORM
External Resources
🤝 Contributing
- Fork the repository
- Create your feature branch (
git checkout -b feature/amazing-feature
) - Commit your changes (
git commit -m 'Add amazing feature'
) - Push to the branch (
git push origin feature/amazing-feature
) - Open a Pull Request
📄 License
MIT License - see the LICENSE file for details.
🙏 Acknowledgments
- Built on uWebSockets.js for high performance
- Inspired by Express.js simplicity
- TypeScript-first approach for better developer experience
🎆 Ready to Build Something Amazing?
👥 Join the Community
💬 Discussions • 🐛 Issues • 🤝 Contributing
❤️ Support the Project
If you find Qwe helpful, please consider:
- ⭐ Starring the repository
- 🐛 Reporting issues and bugs
- 📝 Contributing to the codebase
- 📢 Sharing with the community
Built with ❤️ by @denisetiya
Making TypeScript backend development fast, simple, and enjoyable!