Skip to content

Commit 79b07ad

Browse files
authored
Update middleware documentation on context sharing
1 parent 1494217 commit 79b07ad

File tree

1 file changed

+6
-2
lines changed

1 file changed

+6
-2
lines changed

docs/how-to/middleware.md

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -680,13 +680,17 @@ export const middleware: Route.MiddlewareFunction[] = [
680680

681681
### Sharing Context Between `action` and `loader`
682682

683+
<docs-info>On the server, this approach only works for document POST requests because `context` is scoped to a request. SPA navigation submissions use separate POST/GET requests so you cannot share `context` between them. This pattern always works in `clientMiddleware`/`clientLoader`/`clientAction` because there's no separate HTTP requests.</docs-info>
684+
683685
```tsx
684686
const sharedDataContext = createContext<any>();
685687

686688
export const middleware: Route.MiddlewareFunction[] = [
687689
async ({ request, context }, next) => {
688-
if (request.method === "POST") {
689-
// Set data during action phase
690+
// Set data if it doens't exist
691+
// This will only run once for document requests
692+
// It will run twice (action request + loader request) in SPA navigations
693+
if (!context.get(sharedDataContext)) {
690694
context.set(
691695
sharedDataContext,
692696
await getExpensiveData(),

0 commit comments

Comments
 (0)