Middleware
Middleware allows you to process requests and responses globally. This is useful for tasks like authentication, logging, CORS, and error handling.
Creating Global Middleware
A middleware in Xyra is a function that accepts request, response, and next_handler. Use app.use() to apply it to all routes.
import time
from xyra import App, Request, Response
app = App()
async def logging_middleware(req: Request, res: Response, next_handler):
start_time = time.time()
print(f"Incoming Request: {req.method} {req.url}")
# Pass control to the next middleware or route handler
await next_handler(req, res)
duration_ms = (time.time() - start_time) * 1000
print(f"Finished Request in {duration_ms:.2f}ms")
# Add the middleware to the application
app.use(logging_middleware)
@app.get("/")
def home(req: Request, res: Response):
res.text("Hello, World!")
You must call await next_handler(req, res) to pass control to the next function in the chain. If you don't call it, the request processing will stop.
Route-Specific Middleware
You can also apply middleware to specific routes by passing a list of functions to the middleware argument in the route decorator.
async def auth_middleware(req: Request, res: Response, next_handler):
auth_header = req.headers.get("Authorization")
if not auth_header or auth_header != "Bearer my-secret-token":
res.status(401).json({"error": "Unauthorized"})
return # Stop processing if authentication fails
await next_handler(req, res)
# This middleware will only run for the /protected route
@app.get("/protected", middleware=[auth_middleware])
def protected_route(req: Request, res: Response):
res.json({"message": "You have access to protected data"})
Built-in Middleware
Xyra comes with several built-in middleware for common use cases. These can be imported and used directly.
CORS Middleware
Handles Cross-Origin Resource Sharing (CORS) headers.
from xyra import App
from xyra.middleware import cors
app = App()
# Use CORS middleware
app.use(cors(allowed_origins=["http://localhost:3000"], allow_credentials=True))
GZip Middleware
Compresses responses using GZip for better performance.
from xyra import App
from xyra.middleware import gzip
app = App()
# Use GZip middleware
app.use(gzip())
Rate Limiter Middleware
Limits the number of requests from a single IP address.
from xyra import App
from xyra.middleware import rate_limiter
app = App()
# Use rate limiter middleware (100 requests per minute per IP)
app.use(rate_limiter(requests=100, window=60))
CSRF Middleware
Protects against Cross-Site Request Forgery (CSRF) attacks by validating tokens.
from xyra import App
from xyra.middleware import csrf
app = App()
# Use CSRF middleware
app.use(csrf())
For more built-in middleware options, check the API Reference.