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
Copy file name to clipboardExpand all lines: docs/how-to/middleware.md
+11-9Lines changed: 11 additions & 9 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -276,32 +276,34 @@ const route = {
276
276
};
277
277
```
278
278
279
-
However, 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 a `Record<string, DataStrategy>`object because it is implemented as part of the default [`dataStrategy`] internally. This allows you to take conditional action in your middleware based on the outcome of the executed `loader`/`action` functions.
279
+
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`](../api/data-routers/createBrowserRouter#optsdatastrategy) (`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.
280
280
281
281
Here's an example of the [CMS Redirect on 404][cms-redirect] use case implemented as a client side middleware:
if (Object.values(results).some((r) =>is404(r))) {
292
-
// Check CMS for a redirect
287
+
// Check if we got a 404 from any of our routes and if so, look for a
288
+
// redirect in our CMS
289
+
const found404 =Object.values(results).some(
290
+
(r) =>
291
+
isRouteErrorResponse(r.result) &&
292
+
r.result.status===404,
293
+
);
294
+
if (found404) {
293
295
const cmsRedirect =awaitcheckCMSRedirects(
294
296
request.url,
295
297
);
296
298
if (cmsRedirect) {
297
299
throwredirect(cmsRedirect, 302);
298
300
}
299
301
}
300
-
301
-
returnresults;
302
302
}
303
303
```
304
304
305
+
<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>
306
+
305
307
### When Middleware Runs
306
308
307
309
It is very important to understand _when_ your middlewares will run to make sure your application is behaving as you intend.
0 commit comments