Working with Middleware and Plugins

1. Understanding Middleware Execution Order

Request → CORS → Auth → AuthZ → RateLimit → Transform
       → Route → [Upstream]
       ← Transform ← Logging ← Compress ← Response
      
PhaseOrder
Pre-routingCORS, IP filter
Auth/AuthZIdentity, scopes
Pre-proxyRate limit, transform
ProxyUpstream call
Post-proxyResponse transform, compress, log

2. Configuring Pre-Request Middleware

MiddlewarePurpose
Request ID genAdd correlation ID
Auth checkReject anon early
Schema validateFail fast on bad input
Tenant resolveSet context for downstream

3. Setting Up Post-Request Middleware

MiddlewarePurpose
Response headersAdd security headers
Compressgzip/brotli
Access logStructured JSON
Metrics emitLatency, 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

PluginOutput
file-logLocal JSON file
http-logPOST to log endpoint
syslogOS syslog
tcp-logLogstash/Fluentd
kafka-logKafka topic

7. Configuring Compression Middleware

SettingValue
gzip_min_length1024 bytes
gzip_comp_level4-6
gzip_typesjson, xml, html, css, js, svg
gzip_varyon (sets Vary header)
brotliBetter 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.

PhaseOrder
CORSBefore auth
AuthAfter CORS, before RBAC
RBACAfter 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.

PositionEffect
Before authPer-IP only
After authPer-consumer (preferred)
Both layeredIP DoS + per-user fair use

10. Managing Plugin Dependencies

ConcernResolution
Priority orderHigher number runs first
Shared contextkong.ctx.shared for handoff
Version pinningLock plugin versions in CI
Conflicting pluginsAvoid running 2 auth plugins