reactr-middleware
v1.0.3
Published
Middleware for React Router
Readme
Reactr Middleware
Powerful middleware functionality for React Router v7
Reactr Middleware provides a clean, composable solution for implementing cross-cutting concerns like authentication, logging, rate limiting, and CORS handling in React Router v7 applications.
✨ Features
- 🚀 Easy Integration - Zero breaking changes, works with existing React Router apps
- ⚡ Parallel & Sequential Execution - Run middleware simultaneously or in order
- 📦 Centralized Registry - Organize middleware groups for better maintainability
- 🛡️ Built-in Common Middleware - Auth, CORS, rate limiting, and logging out of the box
- 🎯 TypeScript First - Full type safety and IntelliSense support
- 🔄 Composable - Mix and match middleware to create complex routing logic
- 📚 Well Documented - Comprehensive docs with real-world examples
🚀 Quick Start
Installation
npm install reactr-middleware
# or
yarn add reactr-middleware
# or
pnpm add reactr-middlewareBasic Usage
- Create a middleware configuration:
// middleware.config.ts
import { registerMiddleware, commonMiddlewares } from 'reactr-middleware';
registerMiddleware('protected', [
commonMiddlewares.requireAuth('/login'),
commonMiddlewares.rateLimit(50, 60000),
commonMiddlewares.logger({ includeBody: true })
]);- Use in your route files:
// app/routes/profile.tsx
import { createLoaderFromRegistry } from 'reactr-middleware';
import { useLoaderData } from 'react-router';
import '../middleware.config';
export const loader = createLoaderFromRegistry('protected');
export default function Profile() {
const { middlewareData } = useLoaderData();
return <div>Protected Profile Page</div>;
}- Update your routes config:
// app/routes.ts
import { route, index } from 'reactr-middleware';
export default [
index("routes/home.tsx"),
route("dashboard", "routes/dashboard.tsx"),
route("profile", "routes/profile.tsx"),
];That's it! Your routes now have authentication, rate limiting, and logging.
📋 Built-in Middleware
Authentication
commonMiddlewares.requireAuth('/login')CORS
commonMiddlewares.cors({
origins: ['http://localhost:3000'],
methods: ['GET', 'POST']
})Rate Limiting
commonMiddlewares.rateLimit(100, 60000) // 100 requests per minuteLogging
commonMiddlewares.logger({ includeBody: true })🛠️ Advanced Usage
Parallel Execution
// Run independent middleware simultaneously
export const loader = createLoaderFromRegistry('api', { parallel: true });Custom Middleware
const customMiddleware: Middleware = async (context) => {
// Your custom logic here
const user = await validateUser(context.request);
return {
continue: true,
data: { user, timestamp: Date.now() }
};
};
registerMiddleware('custom', [customMiddleware]);Multiple Groups
// Combine multiple middleware groups
export const loader = createLoaderFromRegistry(['auth', 'security', 'logging']);Error Handling
export const loader = createLoaderFromRegistry('protected', {
rejectOnError: true, // Throw on errors
redirect: '/error' // Or redirect on errors
});📖 Documentation
- Getting Started - Installation and basic setup
- Why Reactr Middleware? - Benefits and use cases
- Creating Middleware - Custom middleware development
- Registry System - Organizing middleware groups
🎯 Use Cases
Perfect for applications that need:
- Authentication & Authorization - Protect routes with user validation
- API Rate Limiting - Prevent abuse with configurable limits
- Cross-Origin Requests - Handle CORS for web APIs
- Request Logging - Track and debug application traffic
- Multi-tenant Applications - Route-level tenant isolation
- Audit Trails - Log sensitive operations for compliance
🔄 Migration
Reactr Middleware is designed for zero breaking changes:
- Install the library
- Gradually migrate routes one by one
- Keep existing code working during transition
- No rush - migrate at your own pace
🤝 Contributing
We welcome contributions! Please see our Contributing Guide for details.
Development Setup
# Clone the repository
git clone https://github.com/DeltaLabs-Community/reactr-middleware.git
cd reactr-middleware
# Install dependencies
npm install
# Run tests
npm test
# Build the library
npm run build📄 License
MIT © Delta Labs
🙏 Acknowledgments
- Built for React Router v7
- Inspired by Express.js middleware patterns
- TypeScript-first design for better developer experience
⭐ Star this project if you find it useful!
