Uploads and request middleware
Uploads and request middleware define the points where an application receives files, serves assets, changes event handling, and shapes requests or responses. The upload service connects browser file selection to backend state events. Middleware adds controlled hooks around event work and the ASGI server boundary. See Backend services for the wider server model, Data models and persistence for durable application data, and Observability and telemetry for request and connection measurements.
File and asset boundary
File upload lifecycle
The upload flow moves file data over HTTP and uses the normal event system for the handler that processes it. A regular handler receives files after the request is buffered. A background handler can consume file chunks while the request arrives. The browser sends a client token and handler name so the server can attach the upload to the correct session event.
This diagram shows how a selected file becomes handler input and then a stored file or client update.
flowchart LR
Select[Select files] --> Request[HTTP multipart upload]
Request --> Identify[Identify token and handler]
Identify --> Buffered[Buffered file event]
Identify --> Stream[Streaming chunk event]
Buffered --> Handler[Run backend handler]
Stream --> Handler
Handler --> Store[Write to upload directory]
Handler --> Update[Return state updates]
Store --> URL[Serve file URL]
The upload component can keep selected files for a later action or send them when a drop event runs. It supports multiple files, progress callbacks, cancellation, rejected-file feedback, and extra values bound to the handler. The public upload API is exposed through the rx namespace. packages/…/upload.py reflex/__init__.py
Streaming upload is for work that must start before the full file is in memory. A bounded hand-off slows the request producer when the background handler does not consume data fast enough. The handler must consume the chunk stream to completion unless the request is cancelled. packages/…/_upload.py packages/…/_upload.py
References: packages/…/upload.py• L75-149 packages/…/_upload.py• L116-251 packages/…/_upload.py• L688-750
Uploaded file access
The upload directory is the server-side store for files that handlers choose to keep. get_upload_dir() creates or returns that directory. get_upload_url() creates a frontend URL under the backend upload endpoint. A handler must write the received file before another request can fetch that URL. packages/…/upload.py
The app adds the upload POST route and the file-serving mount when upload use is detected during compilation or when the upload-use marker remains from an earlier build. The route accepts new files. The file mount serves files from the upload directory and applies a response policy: PDF content may render inline, while other content is forced to download. It also sets X-Content-Type-Options: nosniff. Upload names are reduced to safe relative paths before handlers receive them. This keeps client path segments from selecting an arbitrary server path. reflex/app.py reflex/_upload.py packages/…/_upload.py packages/…/_upload.py
The app records that upload support is in use. This marker keeps the upload routes available on later server builds even when the current compile does not rediscover the upload component. reflex/app.py
The upload directory is application storage, not a record store. If a file belongs to a business record, the record and its file path remain separate concerns. See Data models and persistence for durable application data.
References: packages/…/upload.py• L152-187 reflex/app.py• L1401-1427 reflex/_upload.py• L1-4 packages/…/_upload.py• L79-103 packages/…/_upload.py• L765-814
Build asset delivery
Application assets are files used by the frontend rather than files uploaded by a user. asset() exposes a local app asset or a shared library asset as a URL and adds a short content version. The version changes when file content changes. This lets browsers keep old cached files without hiding a new asset. See Frontend compilation for the wider build flow.
Local assets come from the app asset directory. Shared assets come from the module that calls asset() and are linked into the app's external asset area during frontend work. Each returned asset value also carries an unversioned build-time import path for component or module references. Before a compile, the app removes broken shared-asset links so deleted or moved library files do not keep affecting file watchers. reflex/assets.py reflex/assets.py reflex/assets.py reflex/app.py
References: reflex/assets.py• L23-36 reflex/assets.py• L124-172 reflex/assets.py• L175-303 reflex/app.py• L1288-1294
Request and response middleware
Event middleware contract
Event middleware surrounds backend state handling. A preprocess hook can inspect an event and state before the handler runs. If it returns a state update, the processor sends that update and skips the handler. A postprocess hook can change the update after the handler completes and before the client receives it. reflex/…/middleware.py packages/…/base_state_processor.py
The app registers middleware with add_middleware(). Registration order is used for both preprocess and postprocess hooks. An index lets an app place middleware before an existing entry. Order is part of the event contract when one hook expects another hook to have already run. reflex/…/middleware.py
The event processor applies this contract inside the session-state scope. Event middleware therefore works with the same state and event objects as the handler. ASGI middleware runs one level outside the event processor. The app creates the event processor as a server-lifetime task and supplies the app middleware to it. packages/…/base_state_processor.py reflex/app.py See State and events for the state update boundary.
References: reflex/…/middleware.py• L16-49 reflex/…/middleware.py• L16-85 packages/…/base_state_processor.py• L343-394 reflex/app.py• L1193-1269
Hydration middleware
Hydration is the first state exchange that joins server state with browser state. The built-in HydrateMiddleware recognizes the hydrate event, clears the server copy of client storage, marks the state as not hydrated, and returns the initial state update. The state becomes hydrated only after the load work completes. reflex/…/hydrate_middleware.py
The event processor also has a compatibility path that performs hydration before a normal event when the state has no router data. This protects sessions that send an event before the expected initial exchange finishes. Hydration is both an explicit first event and a safeguard for an incomplete session start. packages/…/base_state_processor.py
This diagram shows the normal relationship between hydration, initial state, and later events.
sequenceDiagram
participant Browser
participant Processor as Event processor
participant State
participant Loads as Load handlers
Browser->>Processor: Hydrate event
Processor->>State: Reset client storage
Processor->>State: Read initial state
Processor-->>Browser: Initial state update
Processor->>Loads: Run load work
Loads-->>Browser: Load state updates
Browser->>Processor: Normal event
References: reflex/…/hydrate_middleware.py• L19-52 packages/…/base_state_processor.py• L360-397
ASGI request boundary
ASGI middleware wraps the server request and response boundary. It can add headers, change response behavior, mount another application, or attach request context before a route or event handler runs. The app exposes api_transformer for Starlette applications or ASGI wrappers. This lets custom APIs and cross-cutting request behavior join the Reflex server without changing event handlers. reflex/app.py reflex/app.py
The app applies each API transformer to the current backend before it builds the outer server wrapper. A Starlette transformer becomes the outer API and mounts the existing backend inside it. A callable transformer wraps the current ASGI application. The outer app then attaches Reflex request context and HTTP CORS handling. Optional telemetry wraps that completed boundary. Upload file serving remains inside the backend routes, so its download and content-sniffing headers affect file responses without changing ordinary API responses. reflex/app.py reflex/app.py packages/…/_upload.py
The event websocket has a separate origin check. In production, the backend accepts its own request origin and the configured deployment origin. Forwarded host and protocol values affect this decision only through the configured trusted proxy chain. This allows a frontend behind a TLS-terminating proxy to connect without treating client-supplied forwarding headers as trusted. Explicit CORS settings still control the allowed origin policy. reflex/app.py reflex/app.py
The socket transport has two boundary guards before event handling. An oversized polling POST is read and rejected with a 400 response, and its socket session is closed so the browser is not left with a half-sent request. A websocket header wrapper mirrors the negotiated protocol in the accept response. These guards keep transport errors and protocol negotiation outside application event handlers. reflex/app.py reflex/app.py
Each request enters an outer ASGI layer that restores Reflex registration and event contexts before it reaches the mounted backend. The outer layer also owns the server lifespan and reports startup or shutdown failures to the ASGI server. This keeps state and event processing available even when the ASGI server creates a fresh context scope for the request. reflex/app.py reflex/app.py
The event connection exposes request metadata through router data. Repeated headers are kept in arrival order instead of being overwritten: cookie values use ; and other repeated fields use , . The ASGI client address is used by default. X-Forwarded-For changes the client IP only when the app has a configured trusted proxy hop count, and the selected address is based on that count. Connection-scoped headers and client data are cached, then copied into each event so a handler cannot change the cached view for later events. This gives event handlers and request customizations a stable view of headers and the client address without trusting an unverified forwarding header. reflex/app.py reflex/app.py reflex/app.py
At connection time, the event namespace can process the browser's boot event before the normal event round trip. It also compares the frontend state schema with the backend schema and tells a stale frontend to reload before hydration. This keeps the first state exchange aligned with the backend that serves it. reflex/app.py
The main customization points have different scopes:
- Event middleware changes state-event input or output.
- ASGI transformers change the server application or mount another API.
- Response middleware changes headers or body handling for a selected route.
- Lifespan hooks manage resources for the full server lifetime.
This diagram shows the broad request order. Event middleware runs only after a request reaches the event processor.
flowchart TB
Request[ASGI request] --> Telemetry[Optional telemetry boundary]
Telemetry --> Context[Reflex root context and lifespan]
Context --> CORS[CORS and websocket origin boundary]
CORS --> Transform[API transformer or mounted API]
Transform --> Route[Route handler]
Route --> UploadHeaders[Upload response headers for file routes]
Route --> SocketGuard[Socket transport guards]
SocketGuard --> Event[Event processor]
Event --> EventMiddleware[Event preprocess and postprocess]
References: reflex/app.py• L371-480 reflex/app.py• L505-878 reflex/app.py• L1018-1025 reflex/app.py• L1141-1185 reflex/app.py• L1328-1381 reflex/app.py• L1401-1427 reflex/app.py• L2621-2975 packages/…/_upload.py• L765-814
Change checklist
When these files or sections are changed, remember to consider these:
- Changing the upload form field or request headers requires matching the browser upload helper, server parser, token lookup, and handler argument resolution.
- Changing buffered or streaming handler rules requires checking the event annotation contract, background-event requirement, request acknowledgement, and cancellation path together.
- Changing upload filename handling or file response headers requires checking both nested paths and browser behavior for HTML, text, and PDF content.
- Changing the upload route or backend path requires checking upload POST requests, generated file URLs, direct file access, and frontend download events.
- Changing asset URL versioning or shared-asset linking requires checking compile-time imports, cache invalidation, and stale-link cleanup.
- Adding event middleware or changing its index requires checking early state updates, hook order, and the update seen by later hooks.
- Changing API transformers or wrapper placement requires checking telemetry, HTTP CORS, websocket origin checks, Reflex context setup, mounted APIs, upload routes, and response middleware order.
- Changing socket polling limits or websocket protocol handling requires checking the pre-transport rejection path, session close behavior, and the protocol fields in the accept response.
- Changing hydration or client-storage reset behavior requires checking the first state update, boot event path, schema mismatch response, and load-handler timing before normal events are accepted.
- Changing request header decoding or trusted proxy settings requires checking repeated cookie fields, repeated non-cookie fields, proxy hop selection, connection-level caching, and the router data seen by event handlers.
- Changing production origin defaults or deployment URL handling requires checking both HTTP CORS and the event websocket handshake behind TLS-terminating or host-rewriting proxies.
Important failure modes
| Trigger | Consequence | Guard |
|---|---|---|
| Upload request lacks the client token or handler header | The server rejects the request before it can create an event | Keep the browser upload helper and upload endpoint contract in sync |
| A streaming handler does not consume all chunks | The producer stops with an error and the upload does not complete normally | Read the chunk iterator until completion or handle cancellation explicitly |
| Upload event arguments are not a JSON object or exceed the limit | The request is rejected before the handler receives its bound values | Send the argument field before the file parts and keep it small |
| A client filename contains unsafe path parts | A stored path could escape the intended upload area | Use the normalized upload name supplied to the handler and keep writes below the upload directory |
| A non-PDF upload is served without the response policy | A browser may render active or unknown content instead of downloading it | Preserve attachment and nosniff handling for non-PDF files |
| Middleware returns an early update when later work is required | The event handler and later preprocess hooks do not run | Reserve early returns for events that are complete after the returned update |
| Middleware registration order changes | A hook can read state or an update before the hook it depends on | Set an explicit index and review the full middleware sequence |
| A normal event arrives before hydration completes | Client storage and server state can start from different values | Keep the hydration safeguard and wait for the initial state exchange |
| An oversized polling POST reaches the transport without the drain guard | The client can remain in a half-sent request while the server waits for another poll | Keep the body-drain, 400 response, and session-close steps together |
| A websocket origin is not accepted by the production policy | The browser cannot open the event connection | Set the frontend deployment origin or configure the trusted proxy chain for forwarded host and protocol values |
| An ASGI wrapper bypasses the app's context, CORS, or telemetry boundary | Routes or event handlers can lose required context, browser access, or request traces | Wrap the existing app and verify the outer request order |
| A forwarding header is trusted without a configured proxy chain | A client can report a false address or handlers can see the wrong client IP | Use the ASGI client address unless trusted proxy hops are configured |
| Repeated request headers are treated as single values | Cookies or forwarded client addresses can be lost or misread by event handlers | Preserve repeated fields in order and apply the field-specific joining rules |
| A handler mutates the shared cached header mapping | Later events on the same connection can see altered request metadata | Copy cached headers into each event before exposing them to state |
Key files
| File | Why to read it |
|---|---|
| packages/…/upload.py | Defines the public upload component, file selection state, progress and cancellation hooks, and upload URL helpers. |
| packages/…/_upload.py | Defines the server upload boundary, buffered and streaming file flow, path safety, and file response headers. |
| packages/…/upload.js | Shows the browser-to-server upload request contract and streamed response handling. |
| reflex/app.py | Builds the backend request boundary and connects optional upload routes, transport guards, CORS, websocket origin checks, API transformers, request context, lifespan, telemetry, event connection metadata, and the ASGI app. |
| reflex/_upload.py | Provides the app-facing upload boundary used to connect upload handling and response headers. |
| reflex/assets.py | Defines local and shared asset URLs, content versioning, and shared-asset cleanup. |
| reflex/…/middleware.py | Defines the event middleware hook contract. |
| reflex/…/middleware.py | Defines middleware registration and hook ordering. |
| reflex/…/hydrate_middleware.py | Defines the initial client-state hydration behavior. |
| packages/…/base_state_processor.py | Shows where hydration and event middleware fit into state event processing. |
| tests/…/test_upload.py | Demonstrates the supported upload, streaming, cancellation, download, and response-security behavior. |