Middleware - React router

October 29, 2025

Middleware in general

Middleware is a pattern that acts a layer between different parts of an application, processing requests and responses as they flow through the system.

Middleware typically has access to the request and response objects as long as the next function.

Each middleware can exacute code, modify request/response objects, end the request-response cycle or call the next middleware.

Common use cases for middleware: Authentication, logging, error handling, CORS, validation and more.

Key advantage is you can use middleware, remove, or reorder them without modifying the core logic.

React router middleware

Middleware runs in a nested chain, executing from parent to child routes on the way "down" to your route handlers, then from your child routes back to parent routes on the way "up" after a response is generated.

TEXT

It's very important to understand when your middleware will run to make sure your application is behaving as you intended.

The steps needed to create a middleware in Framework mode:

1. Create a Context

Middleware uses a a context provider instance to provide data down the middleware chain. You can create a type-safe context objects using createContext

TSX
2. Export middleware from your routes
TSX
3. Update getLoadContext function

If you're using a custom server and a getLoadContext function, you will need to update your implementation to return an instance of RouterContextProvider, instead of a JavaScript object.

Server side middleware

Server middleware runs in the server in framework mode for HTML Document requests and .data requests for subsequent navigations and fetcher calls.

TSX

In a hydrated Framework Mode app, server middlware is designed in such that it prioritizes SPA behaviour and does not create a new network activity by default.

Client side middleware

Client middleware runs in the browser in framework mode and data mode for client-side navigations and fetcher calls. Client middleware differs from server middleware because there's no HTTP requests, so it doesn't have a response bubbling up.

TSX

Client middleware is simpler because since we are already on the client and are always making a "request" to the router when navigating. Client middleware will run on every client navigation, regardless of whether there are loaders to run.