Working with Middleware and Plugins
1. Understanding Middleware Execution Order
Request → CORS → Auth → AuthZ → RateLimit → Transform
→ Route → [Upstream]
← Transform ← Logging ← Compress ← Response
| Phase | Order |
| Pre-routing | CORS, IP filter |
| Auth/AuthZ | Identity, scopes |
| Pre-proxy | Rate limit, transform |
| Proxy | Upstream call |
| Post-proxy | Response transform, compress, log |
2. Configuring Pre-Request Middleware
| Middleware | Purpose |
| Request ID gen | Add correlation ID |
| Auth check | Reject anon early |
| Schema validate | Fail fast on bad input |
| Tenant resolve | Set context for downstream |
3. Setting Up Post-Request Middleware
| Middleware | Purpose |
| Response headers | Add security headers |
| Compress | gzip/brotli |
| Access log | Structured JSON |
| Metrics emit | Latency, status histogram |
4. Creating Custom Middleware
Example: Kong custom plugin (handler.lua)
local CustomHandler = {
VERSION = "1.0.0",
PRIORITY = 1000,
}
function CustomHandler:access(conf)
if not kong.request.get_header("X-Tenant-Id") then
return kong.response.exit(400, { error = "missing tenant" })
end
end
function CustomHandler:header_filter(conf)
kong.response.set_header("X-Processed-By", "custom-plugin")
end
return CustomHandler
5. Implementing Authentication Middleware
Example: JWT auth middleware (Express)
function jwtAuth(req, res, next) {
const header = req.headers["authorization"];
if (!header || !header.startsWith("Bearer ")) {
return res.status(401).json({ error: "missing token" });
}
try {
req.user = jwt.verify(header.slice(7), publicKey, { algorithms: ["RS256"] });
next();
} catch (err) {
res.status(401).json({ error: "invalid token" });
}
}
6. Using Logging Middleware
| Plugin | Output |
file-log | Local JSON file |
http-log | POST to log endpoint |
syslog | OS syslog |
tcp-log | Logstash/Fluentd |
kafka-log | Kafka topic |
7. Configuring Compression Middleware
| Setting | Value |
gzip_min_length | 1024 bytes |
gzip_comp_level | 4-6 |
gzip_types | json, xml, html, css, js, svg |
gzip_vary | on (sets Vary header) |
brotli | Better ratio, slower compress |
8. Setting Up CORS Middleware
See section 7 for full CORS reference. Place CORS middleware early so OPTIONS preflight is answered before auth.
| Phase | Order |
| CORS | Before auth |
| Auth | After CORS, before RBAC |
| RBAC | After auth, before rate-limit |
9. Implementing Rate Limiting Middleware
See section 16. Position rate limiter after auth so limits apply per identified consumer, not per IP.
| Position | Effect |
| Before auth | Per-IP only |
| After auth | Per-consumer (preferred) |
| Both layered | IP DoS + per-user fair use |
10. Managing Plugin Dependencies
| Concern | Resolution |
| Priority order | Higher number runs first |
| Shared context | kong.ctx.shared for handoff |
| Version pinning | Lock plugin versions in CI |
| Conflicting plugins | Avoid running 2 auth plugins |