FallbackMiddleware class
Middleware that falls back to an alternative handler when a response matches a condition.
This is particularly useful for serving Single Page Applications (SPAs) where missing files should fall back to index.html to enable client-side routing.
Basic SPA Usage
final webDir = Directory('web');
final indexFile = File('web/index.html');
pod.webServer.addMiddleware(
FallbackMiddleware(
fallback: StaticRoute.file(indexFile),
on: (response) => response.statusCode == 404,
),
'/**',
);
pod.webServer.addRoute(StaticRoute.directory(webDir), '/**');
Custom Condition Example
pod.webServer.addMiddleware(
FallbackMiddleware(
fallback: errorPageRoute,
on: (response) => response.statusCode >= 500,
),
'/api/**',
);
How It Works
- The middleware wraps the inner handler (typically a StaticRoute)
- Calls the inner handler and receives its response
- If the response matches the condition (e.g., status == 404), calls the fallback handler
- Otherwise, returns the original response
The fallback route automatically has access to the session because all routes in the WebServer are wrapped with session middleware.
- Inheritance
-
- Object
- MiddlewareObject
- FallbackMiddleware
Constructors
- FallbackMiddleware({required Route fallback, required bool on(Response)})
-
Creates a new FallbackMiddleware
const
Properties
- asMiddleware → Middleware
-
Returns this MiddlewareObject as a Middleware function.
no setterinherited
- fallback → Route
-
The fallback route to use when the condition matches
final
- hashCode → int
-
The hash code for this object.
no setterinherited
- on → bool Function(Response)
-
The condition function that determines when to use the fallback
final
- runtimeType → Type
-
A representation of the runtime type of the object.
no setterinherited
Methods
-
call(
Handler next) → Handler -
The implementation of this MiddlewareObject
override
-
injectIn(
Router< Handler> router) → void -
Use this middleware on
routeron path/. Override to use on a different path.inherited -
noSuchMethod(
Invocation invocation) → dynamic -
Invoked when a nonexistent method or property is accessed.
inherited
-
toString(
) → String -
A string representation of this object.
inherited
Operators
-
operator ==(
Object other) → bool -
The equality operator.
inherited