Skip to content

docs(start): add dynamic middleware section with authorization example#6815

Merged
schiller-manuel merged 5 commits intoTanStack:mainfrom
ovitorhilario:docs/dynamic-middleware
Mar 5, 2026
Merged

docs(start): add dynamic middleware section with authorization example#6815
schiller-manuel merged 5 commits intoTanStack:mainfrom
ovitorhilario:docs/dynamic-middleware

Conversation

@ovitorhilario
Copy link
Contributor

@ovitorhilario ovitorhilario commented Mar 3, 2026

Add Dynamic Middleware Documentation

This PR adds an example to the middleware docs covering the dynamic middleware pattern.

What is dynamic middleware?

Unlike static middlewares, which are created once and reused across routes, dynamic middleware is a function that returns a middleware instance. This allows it to accept parameters at call time and behave differently depending on the context.

What's covered

  • A static authMiddleware as a base, which validates the session and injects it into context
  • A dynamic authorizationMiddleware that accepts a permissions parameter and validates access against it
  • Usage with createServerFn, showing how to pass a dynamic middleware instance in the .middleware([]) array

Why authorization?

Authorization is a common use case for this pattern, as the required permissions vary per server function.

Summary by CodeRabbit

  • Documentation
    • Added a "Middleware Factories" section explaining static vs. dynamic middleware and when to use each.
    • Provides usage patterns for reusable, parameterized middleware, composition with existing middleware, and per-function context checks.
    • Includes authentication and authorization examples demonstrating common integration scenarios.

@github-actions github-actions bot added the documentation Everything documentation related label Mar 3, 2026
@coderabbitai
Copy link
Contributor

coderabbitai bot commented Mar 3, 2026

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 2acf4f41-6445-4b0f-9e1f-822a8745eb12

📥 Commits

Reviewing files that changed from the base of the PR and between 30a129f and e251ac8.

📒 Files selected for processing (1)
  • docs/start/framework/react/guide/middleware.md

📝 Walkthrough

Walkthrough

Adds a "Middleware Factories" section to the React middleware guide that documents static vs. dynamic middleware factories, a parameterized middleware-factory pattern, authentication (static base middleware) and authorization (factory) examples, middleware composition, and per-function server usage snippets.

Changes

Cohort / File(s) Summary
Documentation
docs/start/framework/react/guide/middleware.md
Appended a "Middleware Factories" section covering static vs. dynamic middleware factories, parameterized factory creation, examples for authentication (static base middleware) and authorization (middleware factory), composition examples, and per-function server usage snippets. No code exports changed; documentation-only edits.

Estimated code review effort

🎯 1 (Trivial) | ⏱️ ~3 minutes

Poem

🐰
I hopped through lines where middleware grows,
Built steady guards and ones that bloom on clothes,
Static roots for certainty, factories for spring,
I tie them up together — a secure little ring,
Nibble a carrot, then off I go, code in tow.

🚥 Pre-merge checks | ✅ 3
✅ Passed checks (3 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately captures the main change: adding a dynamic middleware section with authorization examples to the documentation.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@nx-cloud
Copy link

nx-cloud bot commented Mar 3, 2026

View your CI Pipeline Execution ↗ for commit e251ac8

Command Status Duration Result
nx affected --targets=test:eslint,test:unit,tes... ✅ Succeeded <1s View ↗
nx run-many --target=build --exclude=examples/*... ✅ Succeeded 2s View ↗

☁️ Nx Cloud last updated this comment at 2026-03-05 18:59:55 UTC

@github-actions
Copy link

github-actions bot commented Mar 3, 2026

Bundle Size Benchmarks

  • Commit: 861f319bbeb8
  • Measured at: 2026-03-05T18:46:53.975Z
  • Baseline source: history:2217f7c3f19f
  • Dashboard: bundle-size history
Scenario Current (gzip) Delta vs baseline Raw Brotli Trend
react-router.minimal 86.84 KiB +269 B (+0.30%) 273.33 KiB 75.44 KiB ▁▁▁▁▁▁▁▁▁▁█
react-router.full 89.88 KiB +281 B (+0.31%) 283.67 KiB 78.18 KiB ▁▁▁▁▁▁▁▁▁▁█
solid-router.minimal 36.17 KiB +299 B (+0.81%) 108.44 KiB 32.49 KiB ▁▁▁▁▁▁▁▁▁▁█
solid-router.full 40.50 KiB +293 B (+0.71%) 121.49 KiB 36.40 KiB ▁▁▁▁▁▁▁▁▁▁█
vue-router.minimal 52.03 KiB +287 B (+0.54%) 148.42 KiB 46.71 KiB ▁▁▁▁▁▁▁▁▁▁█
vue-router.full 56.85 KiB +306 B (+0.53%) 164.01 KiB 51.04 KiB ▁▁▁▁▁▁▁▁▁▁█
react-start.minimal 99.40 KiB +295 B (+0.29%) 312.48 KiB 85.98 KiB ▁▁▁▁▁▁▁▁▁▁█
react-start.full 102.78 KiB +288 B (+0.27%) 322.29 KiB 88.82 KiB ▁▁▁▁▁▁▁▁▁▁█
solid-start.minimal 48.49 KiB +307 B (+0.62%) 146.03 KiB 42.85 KiB ▁▁▁▁▁▁▁▁▁▁█
solid-start.full 53.96 KiB +290 B (+0.53%) 161.98 KiB 47.51 KiB ▁▁▁▁▁▁▁▁▁▁█

Trend sparkline is historical gzip bytes ending with this PR measurement; lower is better.

- On the server, nothing is tree-shaken, so all code used in middleware will be included in the server bundle.
- On the client, all server-specific code is removed from the client bundle. This means any code used in the `server` method is always removed from the client bundle. `data` validation code will also be removed.

## Dynamic Middleware
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

rather call it middleware factories

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done, renamed throughout the section.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@docs/start/framework/react/guide/middleware.md`:
- Around line 799-802: The example shows invalid syntax by splitting the method
name from its call (the `.server` token is separated from `()` by a comment);
update the `authMiddleware` example so `createMiddleware().server()` is written
as a single call (or remove the redundant declaration and leave a comment
referring to the earlier `authMiddleware` definition) — ensure you update the
`authMiddleware` and `createMiddleware` usage to use valid call syntax
(`.server()` together) rather than inserting a comment between the method name
and its parentheses.

ℹ️ Review info

Configuration used: defaults

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between eb27765 and 6b1872e.

📒 Files selected for processing (1)
  • docs/start/framework/react/guide/middleware.md

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@docs/start/framework/react/guide/middleware.md`:
- Around line 799-802: Remove the redundant authMiddleware declaration block
(the createMiddleware()... .server async ({ next, request }) stub) since
authMiddleware is already fully defined earlier; locate the authMiddleware
symbol and delete this abbreviated redeclaration, or if you intend it as a
self-contained reference instead of deletion, replace the stub with a clear
comment stating "Reference only — full implementation shown above" so readers
aren’t confused.

ℹ️ Review info

Configuration used: defaults

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 6b1872e and 30a129f.

📒 Files selected for processing (1)
  • docs/start/framework/react/guide/middleware.md

Comment on lines +799 to +802
export const authMiddleware = createMiddleware()
.server(async ({ next, request }) => {
// ... (implementation from authentication example above)
})
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor

Remove the redundant authMiddleware declaration.

The authMiddleware is already fully defined in the authentication example above (lines 775-787). Redeclaring it here with an abbreviated comment creates unnecessary redundancy and may confuse readers.

📝 Suggested improvement

Option 1 (recommended): Remove the redundant declaration entirely since readers can reference the earlier complete example:

-export const authMiddleware = createMiddleware()
-  .server(async ({ next, request }) => {
-    // ... (implementation from authentication example above)
-  })
-
 type Permissions = Record<string, string[]>

Option 2: If showing the full structure is intentional for a self-contained example, add a comment clarifying this is a reference:

+// Using authMiddleware from the authentication example above
 export const authMiddleware = createMiddleware()
   .server(async ({ next, request }) => {
-    // ... (implementation from authentication example above)
+    const session = await auth.getSession({ headers: request.headers })
+    if (!session) {
+      throw new Error('Unauthorized')
+    }
+    return await next({
+      context: { session },
+    })
   })
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
export const authMiddleware = createMiddleware()
.server(async ({ next, request }) => {
// ... (implementation from authentication example above)
})
Suggested change
export const authMiddleware = createMiddleware()
.server(async ({ next, request }) => {
// ... (implementation from authentication example above)
})
// Using authMiddleware from the authentication example above
export const authMiddleware = createMiddleware()
.server(async ({ next, request }) => {
const session = await auth.getSession({ headers: request.headers })
if (!session) {
throw new Error('Unauthorized')
}
return await next({
context: { session },
})
})
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@docs/start/framework/react/guide/middleware.md` around lines 799 - 802,
Remove the redundant authMiddleware declaration block (the createMiddleware()...
.server async ({ next, request }) stub) since authMiddleware is already fully
defined earlier; locate the authMiddleware symbol and delete this abbreviated
redeclaration, or if you intend it as a self-contained reference instead of
deletion, replace the stub with a clear comment stating "Reference only — full
implementation shown above" so readers aren’t confused.

@schiller-manuel schiller-manuel merged commit 64dee75 into TanStack:main Mar 5, 2026
4 checks passed
@codspeed-hq
Copy link

codspeed-hq bot commented Mar 5, 2026

Merging this PR will not alter performance

✅ 5 untouched benchmarks


Comparing ovitorhilario:docs/dynamic-middleware (e251ac8) with main (64dee75)1

Open in CodSpeed

Footnotes

  1. No successful run was found on main (861f319) during the generation of this report, so 64dee75 was used instead as the comparison base. There might be some changes unrelated to this pull request in this report.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

documentation Everything documentation related

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants