How Middleware Works
Middleware executes in the order it’s registered, forming a chain where each middleware can:- Execute code before the route handler
- Call
c.Next()to pass control to the next middleware/handler - Execute code after the next handler returns
- Terminate the request early without calling
c.Next()
The Next() Function
Thec.Next() function passes control to the next middleware or route handler in the stack:
Without Next()
If you don’t callc.Next(), the request terminates and subsequent middleware/handlers don’t execute:
Global Middleware
Global middleware applies to all routes:Path-Specific Middleware
Apply middleware to specific paths or path prefixes:Multiple Paths
Apply middleware to multiple specific paths:Route-Level Middleware
Attach middleware directly to specific routes:Middleware Execution Order
Middleware executes in this order:- Global middleware (registered with
app.Use()) - Group middleware (registered on route groups)
- Route-level middleware (passed to route methods)
- Route handler
Creating Custom Middleware
Basic Middleware
Configurable Middleware
Common Middleware Patterns
Authentication
CORS
Request Validation
Response Timing
Error Handling in Middleware
Return errors from middleware to trigger the error handler:RestartRouting
Restart routing from the beginning after modifying the path:Built-in Middleware
Fiber provides many built-in middleware packages:Logger
HTTP request/response logging
Recover
Recover from panics
CORS
Cross-Origin Resource Sharing
Compress
Response compression
Limiter
Rate limiting
Timeout
Request timeout handling
CSRF
CSRF protection
Session
Session management
Best Practices
Always handle Next() errors
Always handle Next() errors
Check and return errors from
c.Next() to ensure proper error propagation.Keep middleware focused
Keep middleware focused
Each middleware should have a single responsibility for maintainability.
Use Locals for request-scoped data
Use Locals for request-scoped data
Store data for the current request using
c.Locals().Order matters
Order matters
Register middleware in the correct order - authentication before authorization, logging before everything.
See Also
Context
Work with request and response data
Error Handling
Handle errors in middleware
Grouping
Apply middleware to route groups
Routing
Define routes and handlers