You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Client middleware runs in the browser in framework and data mode for client-side navigations and fetcher calls. Client middleware is different because there's no HTTP [`Request`][request], so it doesn't bubble up anything via the `next`function:
259
+
Client middleware runs in the browser in framework and data mode for client-side navigations and fetcher calls. Client middleware differs from server middleware because there's no HTTP Request, so it doesn't have a `Response` to bubble up. In most cases, you can just ignore the return value from `next`and return nothing from your middleware on the client:
There may be _some_ cases where you want to do some post-processing based on the result of the loaders/action. In lieu of a `Response`, client middleware bubbles up the value returned from the active [`dataStrategy`][datastrategy] (`Record<string, DataStrategyResult>` - keyed by route id). This allows you to take conditional action in your middleware based on the outcome of the executed `loader`/`action` functions.
282
+
283
+
Here's an example of the [CMS Redirect on 404][cms-redirect] use case implemented as a client side middleware:
// Check if we got a 404 from any of our routes and if so, look for a
290
+
// redirect in our CMS
291
+
const found404 =Object.values(results).some(
292
+
(r) =>
293
+
isRouteErrorResponse(r.result) &&
294
+
r.result.status===404,
295
+
);
296
+
if (found404) {
297
+
const cmsRedirect =awaitcheckCMSRedirects(
298
+
request.url,
299
+
);
300
+
if (cmsRedirect) {
301
+
throwredirect(cmsRedirect, 302);
302
+
}
303
+
}
304
+
}
305
+
```
306
+
307
+
<docs-warning>In a server middleware, you shouldn't be messing with the `Response` body and should only be reading status/headers and setting headers. Similarly, this value should be considered read-only in client middleware because it represents the "body" or "data" for the resulting navigation which should be driven by loaders/actions - not middleware. This also means that in client middleware, there's usually no need to return the results even if you needed to capture it from `await next()`;</docs-warning>
308
+
282
309
### When Middleware Runs
283
310
284
311
It is very important to understand _when_ your middlewares will run to make sure your application is behaving as you intend.
0 commit comments