Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
124 commits
Select commit Hold shift + click to select a range
94c6038
Add signed browser sessions and session-bound client tokens
masenf Sep 30, 2026
a987ce7
Document session primitive regression tests
masenf Sep 30, 2026
b592c65
Scope signed sessions to their issuing app and fix portable secret tests
masenf Oct 14, 2026
44c4b4e
Keep frontend cleanup locking coverage with persistent session secrets
masenf Oct 14, 2026
d8a70b1
Authorize browser state through session-aware HTTP and WebSocket tran…
masenf Sep 30, 2026
1eb1a60
Adapt connect hydration tests to session-aware fixtures
masenf Oct 5, 2026
05fa726
Use the validated root context for streamed event fallback
masenf Oct 5, 2026
9120624
Scope custom sockets and renew authenticated browser sessions
masenf Oct 14, 2026
ebed735
Preserve the public database session helper when loading App
masenf Oct 14, 2026
c21c1a9
Persist in-band browser sessions without delaying hydration
masenf Sep 30, 2026
8308fa6
Preserve session cookies and hydration auth through transport warmup
masenf Oct 5, 2026
9833bb2
Coordinate cold sessions before warming browser transports
masenf Oct 5, 2026
579c45e
Renew idle sessions and recover cookie readiness without losing queue…
masenf Oct 14, 2026
9e9b3b6
Keep HTTP readiness pending through cookie replacement reconnects
masenf Oct 14, 2026
2dc17d8
Exercise enforced sessions across servers and browsers and document m…
masenf Sep 30, 2026
32324b7
Exercise session recovery and preserve production restart settings
masenf Oct 14, 2026
ebba877
Keep the Granian session test out of the global BaseState registry
masenf Oct 14, 2026
d5e211b
Document HTTP readiness during cookie replacement reconnects
masenf Oct 14, 2026
f03175f
Read the session secret key from REFLEX_SECRET_KEY only
FarhanAliRaza Nov 17, 2026
056313c
Merge session-token-primitives into session-transport
FarhanAliRaza Nov 17, 2026
63e635b
Merge session-transport into session-frontend
FarhanAliRaza Nov 17, 2026
6c84657
Merge session-frontend into session-integration
FarhanAliRaza Nov 17, 2026
38fe963
Document REFLEX_SECRET_KEY and safe key changes
FarhanAliRaza Nov 17, 2026
0f1b8c6
Merge main into session-token-primitives
FarhanAliRaza Nov 17, 2026
d5bf4c0
Raise the reflex-base floor for reflex_base.session
FarhanAliRaza Nov 17, 2026
27e4900
Merge session-token-primitives into session-transport
FarhanAliRaza Nov 17, 2026
b4d364a
Assert complete session messages and isolate config defaults
FarhanAliRaza Nov 17, 2026
1b1ed03
Merge remote-tracking branch 'upstream/main' into pr-7361
FarhanAliRaza Nov 24, 2026
45d2bca
Reject a short REFLEX_SECRET_KEY when reflex run starts
FarhanAliRaza Nov 24, 2026
426396a
Merge branch 'pr-7361' into pr-7362
FarhanAliRaza Nov 24, 2026
24c92b7
Fix session exchange for unstored cookies, same-host pages and shared…
FarhanAliRaza Nov 24, 2026
7a2791a
Merge session-transport into session-frontend and fix session lifecyc…
FarhanAliRaza Nov 24, 2026
08c88ca
Merge branch 'pr-7363' into pr-7364
FarhanAliRaza Nov 24, 2026
8f8c50d
Document session renewal, trusted origins and plain HTTP hosts
FarhanAliRaza Nov 24, 2026
3be8196
Type the session exchange error and adapt the frontend package tests
FarhanAliRaza Nov 24, 2026
310aaa4
Merge branch 'pr-7363' into pr-7364
FarhanAliRaza Nov 24, 2026
8eacdf1
Enforce session ownership by default
FarhanAliRaza Nov 24, 2026
f7c467c
Merge branch 'pr-7361' into pr-7362
FarhanAliRaza Nov 24, 2026
f250df6
Merge branch 'pr-7362' into pr-7363
FarhanAliRaza Nov 24, 2026
42269ed
Merge branch 'pr-7363' into pr-7364
FarhanAliRaza Nov 24, 2026
e5ce4c5
Keep unit tests and benchmarks on a compatibility session mode
FarhanAliRaza Nov 24, 2026
dc7b4e4
Merge branch 'pr-7362' into pr-7363
FarhanAliRaza Nov 24, 2026
ea17694
Merge branch 'pr-7363' into pr-7364
FarhanAliRaza Nov 24, 2026
364e3aa
Merge branch 'pr-7361' into pr-7362
FarhanAliRaza Nov 24, 2026
b1791be
Merge branch 'pr-7362' into pr-7363
FarhanAliRaza Nov 24, 2026
6715188
Merge branch 'pr-7363' into pr-7364
FarhanAliRaza Nov 24, 2026
d5fe340
Merge remote-tracking branch 'upstream/main' into pr-7361
FarhanAliRaza Nov 24, 2026
1da52ce
Give the session check, the token rule and the socket credential one …
FarhanAliRaza Nov 24, 2026
eb7dc36
Merge branch 'pr-7362' into pr-7363
FarhanAliRaza Nov 24, 2026
844c0f8
Track the session exchange with its abort controller only
FarhanAliRaza Nov 24, 2026
31cd10a
Merge branch 'pr-7363' into pr-7364
FarhanAliRaza Nov 24, 2026
903e831
Document the one-minute exchange credential
FarhanAliRaza Nov 24, 2026
6660d41
End a browser session at a maximum age
FarhanAliRaza Nov 24, 2026
8ebf492
Merge branch 'pr-7363' into pr-7364
FarhanAliRaza Nov 24, 2026
2fa93dc
Merge branch 'pr-7362' into pr-7363
FarhanAliRaza Nov 24, 2026
29b1493
Document the maximum session age
FarhanAliRaza Nov 24, 2026
3d3cf0a
Reject a blank REFLEX_SECRET_KEY at startup
FarhanAliRaza Nov 24, 2026
5f27de5
Merge branch 'pr-7361' into pr-7362
FarhanAliRaza Nov 24, 2026
20066d0
Address review findings on the session transport
FarhanAliRaza Nov 24, 2026
cc21438
Merge branch 'pr-7362' into pr-7363
FarhanAliRaza Nov 24, 2026
0442b43
Address review findings on the frontend session lifecycle
FarhanAliRaza Nov 24, 2026
b2c666a
Merge session-frontend and address review findings on the guide and t…
FarhanAliRaza Nov 24, 2026
c366510
Generate a key for a blank REFLEX_SECRET_KEY and share it with workers
FarhanAliRaza Nov 24, 2026
c729a2a
Merge branch 'pr-7361' into pr-7362
FarhanAliRaza Nov 24, 2026
e5c53a3
Merge branch 'pr-7362' into pr-7363
FarhanAliRaza Nov 24, 2026
62cf3b2
Merge branch 'pr-7363' into pr-7364
FarhanAliRaza Nov 24, 2026
79c431f
Keep warn as the session mode default in the primitives
FarhanAliRaza Nov 24, 2026
dcba6b6
Merge branch 'pr-7361' into pr-7362
FarhanAliRaza Nov 24, 2026
8c111a0
Restore the enforce value of the session mode setting
FarhanAliRaza Nov 24, 2026
8721945
Merge branch 'pr-7361' into pr-7362
FarhanAliRaza Nov 24, 2026
6636a2d
Renew cookie-backed sockets at the session endpoint only
FarhanAliRaza Nov 24, 2026
ecdf167
Merge branch 'pr-7362' into pr-7363
FarhanAliRaza Nov 24, 2026
d17b38d
Adapt browser tests to the scoped token key and stop holding uploads …
FarhanAliRaza Nov 24, 2026
2709fda
Let the storage browser test ignore the session cookie and refresh hint
FarhanAliRaza Nov 24, 2026
8a2f827
Merge session-frontend and enforce session ownership by default
FarhanAliRaza Nov 24, 2026
f934c25
Merge branch 'pr-7363' into pr-7364
FarhanAliRaza Nov 24, 2026
0102822
Document session renewal at the endpoint and the session route for pr…
FarhanAliRaza Nov 25, 2026
5539139
Connect a socket without an ambient event context
FarhanAliRaza Nov 25, 2026
b93c236
Adapt two browser tests to the enforced default and the localhost har…
FarhanAliRaza Nov 25, 2026
f2cb365
Merge branch 'pr-7362' into pr-7363
FarhanAliRaza Nov 25, 2026
0ee0c76
Merge branch 'pr-7363' into pr-7364
FarhanAliRaza Nov 25, 2026
3e7ce1a
Show the user an upload that the server rejects
FarhanAliRaza Nov 25, 2026
199bd76
Merge branch 'pr-7363' into pr-7364
FarhanAliRaza Nov 25, 2026
1c7aa71
Word the rejected-upload error for the user in production
FarhanAliRaza Nov 25, 2026
78a3800
Merge branch 'pr-7363' into pr-7364
FarhanAliRaza Nov 25, 2026
e525408
Document the message for an upload without a valid session
FarhanAliRaza Nov 25, 2026
ab09ed7
Compare the port of a same-origin session request by value
FarhanAliRaza Nov 25, 2026
9b4b055
Merge branch 'pr-7362' into pr-7363
FarhanAliRaza Nov 25, 2026
9cbdb0c
Merge branch 'pr-7363' into pr-7364
FarhanAliRaza Nov 25, 2026
cef90d9
Proxy the session route in the Caddyfile examples and qualify two gui…
FarhanAliRaza Nov 25, 2026
3d574be
Keep a denied or lasting-failure exchange from restarting holds
FarhanAliRaza Nov 25, 2026
44e1343
Merge branch 'pr-7363' into pr-7364
FarhanAliRaza Nov 25, 2026
77d4caa
Send both cookie forms in local HTTP development
FarhanAliRaza Nov 25, 2026
a1a89ae
Merge branch 'pr-7363' into pr-7364
FarhanAliRaza Nov 25, 2026
84836e3
Merge branch 'pr-7362' into pr-7363
FarhanAliRaza Nov 25, 2026
e2f2528
Document the two cookie forms of local HTTP development
FarhanAliRaza Nov 25, 2026
ae217d3
Select the secure session cookie by name in the browser tests
FarhanAliRaza Nov 25, 2026
948b4b0
Send one session cookie in local HTTP development
FarhanAliRaza Nov 25, 2026
24f8b4e
Merge branch 'pr-7363' into pr-7364
FarhanAliRaza Nov 25, 2026
14e0ebf
Merge branch 'pr-7362' into pr-7363
FarhanAliRaza Nov 25, 2026
d1ca4f5
Revert "Select the secure session cookie by name in the browser tests"
FarhanAliRaza Nov 25, 2026
3911e50
Revert "Document the two cookie forms of local HTTP development"
FarhanAliRaza Nov 25, 2026
eae4c38
Parse the session token mode once per environment value
FarhanAliRaza Nov 25, 2026
d7c860d
Merge branch 'pr-7362' into pr-7363
FarhanAliRaza Nov 25, 2026
3cda7b4
Merge branch 'pr-7363' into pr-7364
FarhanAliRaza Nov 25, 2026
8d6795d
Remove the per-tab session flag from the upload hold
FarhanAliRaza Nov 25, 2026
5135e0f
Merge branch 'pr-7363' into pr-7364
FarhanAliRaza Nov 25, 2026
c333842
Run the benchmarks without session ownership checks
FarhanAliRaza Nov 25, 2026
7f68049
Merge branch 'pr-7363' into pr-7364
FarhanAliRaza Nov 25, 2026
53f3b59
Merge branch 'pr-7362' into pr-7363
FarhanAliRaza Nov 25, 2026
4648e45
Give the restarted backend a new token manager in the restart test
FarhanAliRaza Nov 25, 2026
f34272a
Merge remote-tracking branch 'upstream/main' into pr-7362
FarhanAliRaza Nov 25, 2026
14f1b38
Merge branch 'pr-7362' into pr-7363
FarhanAliRaza Nov 25, 2026
855f835
Merge branch 'pr-7363' into pr-7364
FarhanAliRaza Nov 25, 2026
5154533
Merge remote-tracking branch 'upstream/main' into pr-7364
FarhanAliRaza Nov 25, 2026
96ed981
Set a secret key for the backend restart test
FarhanAliRaza Nov 30, 2026
5a15f86
Document the secret key and proxy route for an upgrade, and keep enforce
FarhanAliRaza Nov 30, 2026
005d5a7
Restructure the browser sessions guide for the reader
FarhanAliRaza Nov 30, 2026
13c5731
Cut the browser sessions guide to what a reader acts on
FarhanAliRaza Nov 30, 2026
e6d1cc3
Test every session outcome in the browser under enforce
FarhanAliRaza Nov 30, 2026
bc2fb8d
Pick the upload toast by its title in the session tests
FarhanAliRaza Nov 30, 2026
f60672d
Set the internal skip-compile variable in the prod restart test
FarhanAliRaza Nov 30, 2026
e5ba25c
Say that a backend outside reflex run needs REFLEX_SECRET_KEY for its…
FarhanAliRaza Nov 30, 2026
7d859b8
Document the arguments of the session test helpers
FarhanAliRaza Nov 30, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 6 additions & 3 deletions docker-example/app-platform-backend/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -36,9 +36,12 @@ Deploy a `redis` instance on the vnet.

The backend is built by the `Dockerfile` in this directory. When deploying the
backend, be sure to set REFLEX_REDIS_URL=redis://internal-redis-hostname to connect to
the redis service, and REFLEX_DEPLOY_URL to the public URL of the static frontend
(e.g. `https://app.example.com`). Unless `cors_allowed_origins` is set explicitly, the
backend only accepts websocket connections from its own origin and from that URL.
the redis service, REFLEX_DEPLOY_URL to the public URL of the static frontend
(e.g. `https://app.example.com`), and REFLEX_SECRET_KEY to a random value of at least
32 bytes, stored as a secret. Give every replica and every deploy the same
REFLEX_SECRET_KEY: replicas with different keys reject each other's browser sessions.
Unless `cors_allowed_origins` is set explicitly, the backend only accepts websocket
connections from its own origin and from that URL.
Comment thread
FarhanAliRaza marked this conversation as resolved.
Resolved

With redis available, each replica runs up to 8 workers by default
(`2 * cpu_count + 1`, capped at 8). When using Granian, set `GRANIAN_WORKERS`
Expand Down
2 changes: 1 addition & 1 deletion docker-example/production-compose/Caddyfile
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

encode gzip

@backend_routes path /_event/* /ping /_health /_upload /_upload/*
@backend_routes path /_event/* /ping /_health /_upload /_upload/* /_reflex/session
handle @backend_routes {
reverse_proxy app:8000
}
Expand Down
7 changes: 6 additions & 1 deletion docker-example/production-compose/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -41,9 +41,14 @@ frontend out of the `app` image, so compose always builds `app` first.
## Run Reflex Production Service

```bash
DOMAIN=example.com docker compose up
DOMAIN=example.com REFLEX_SECRET_KEY=<random value> docker compose up
```

Generate `REFLEX_SECRET_KEY` once, for example with
`python -c "import secrets; print(secrets.token_hex(32))"`, and keep it in a
secret store. Use the same value on every run: without it, all browser sessions
reset whenever the container restarts.

The app should be available at the specified domain via HTTPS. Certificate
provisioning will occur automatically and may take a few minutes.

Expand Down
2 changes: 2 additions & 0 deletions docker-example/production-compose/compose.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@ services:
app:
environment:
REFLEX_DB_URL: sqlite:///data/reflex.db
# Signs the browser session cookies. Without it, sessions reset on restart.
REFLEX_SECRET_KEY: ${REFLEX_SECRET_KEY:-}
build:
context: .
volumes:
Expand Down
2 changes: 1 addition & 1 deletion docker-example/production/Caddyfile
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

encode gzip

@backend_routes path /_event/* /ping /_health /_upload /_upload/*
@backend_routes path /_event/* /ping /_health /_upload /_upload/* /_reflex/session
handle @backend_routes {
reverse_proxy localhost:8000
}
Expand Down
4 changes: 4 additions & 0 deletions docs/api-routes/overview.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,10 @@ The API transformer provides a way to:

This is useful for creating a backend API that can be used for purposes beyond your Reflex app, or for integrating Reflex with existing backend services.

Routes accessing Reflex state inherit the requesting browser's session. See
[browser sessions](/docs/api-routes/sessions/) for ownership checks, trusted
server-side access, and deployment configuration.

## Using API Transformer

You can set the `api_transformer` parameter when initializing your Reflex app:
Expand Down
199 changes: 199 additions & 0 deletions docs/api-routes/sessions.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,199 @@
---
title: Browser Sessions
---

# Browser Sessions

Reflex binds each tab's state to a signed browser session. Two values identify
a tab:

- The **session cookie** is an HTTP-only cookie that the backend signs. Page
scripts cannot read it.
- The **client token** (`client_token`) identifies one tab of that session. It
alone does not give access to the tab's state.

A session establishes ownership of state, not a user identity or login.
Authentication and authorization still belong in your app or AuthPlugin.

## Modes

```md alert warning
# Keep `enforce` in production.

Only `enforce` stops a client that knows a client token from reading and
changing that tab's state. `warn` and `off` turn that protection off. Use one
only to keep a broken deployment running while you fix the code that fails
under `enforce`, then remove it.
```

| Mode | Behavior |
| --- | --- |
| `enforce` (default) | State access and uploads need the session that owns the client token. A tab that presents a client token its session does not own gets a new one and fresh state. |
| `warn` | Escape hatch. Allows state access that the session does not own and logs a warning that names the call site. |
| `off` | Escape hatch. Disables ownership checks. |

## Settings

| Setting | Default | What it controls |
| --- | --- | --- |
| `REFLEX_SECRET_KEY` (environment) | A temporary key for each `reflex run` | The keys that sign session cookies. See [Signing keys](#signing-keys). |
| `REFLEX_SESSION_TOKEN_MODE` (environment) | `enforce` | See [Modes](#modes). Set it on every backend worker and replica. |
| `session_token_ttl` | Seven days | How long one session cookie is valid. The browser renews it while the tab is open. |
| `session_token_max_age` | Seven days | The maximum age of a session. Renewal cannot extend a session past it. |
| `session_token_refresh_interval` | Half of `session_token_ttl` | When the browser renews the cookie. |

The `session_token_*` settings are `rx.Config` options, in seconds. Set
`session_token_ttl` below `session_token_max_age` to end idle sessions sooner
while active ones last up to the maximum age.

Under `enforce`, a session that reaches its maximum age ends: at the next
renewal the tab gets a new session, a new client token, and fresh state.
Uploads before that renewal return 403, and the page shows "Your session has
expired. Reload the page and try again."

## Upgrading

Before you deploy the upgrade:

- Set `REFLEX_SECRET_KEY` on every backend (see [Signing keys](#signing-keys)).
Without it, every restart resets the state of all tabs, and replicas reject
each other's sessions.
- Route `/_reflex/session` to the backend in your reverse proxy, as you route
`/_event` and `/_upload`. Without it, the browser never stores the session
cookie, so each reload starts with fresh state.

After the upgrade:

- Tabs that were open during the upgrade get a new client token and lose their
state once.
- Server code that changes the state of another client, such as a broadcast
or a webhook that calls `app.modify_state`, raises
`SessionAuthorizationError`. Pass `session_token=SessionToken.SYSTEM` (see
[Server-side state access](#server-side-state-access)). This includes
`app.modify_state` with the token of an `rx.SharedState`.
- A client that is not a browser must use the client token that the backend
sends (see [Clients that are not browsers](#clients-that-are-not-browsers)).

Test the upgrade under `enforce` and fix your code before you deploy. If a
deployment breaks on code that you cannot fix at once, `warn` keeps it running
and logs each call site that needs a fix. Return to `enforce` as soon as you
can.

## Signing keys

```md alert warning
# Set one `REFLEX_SECRET_KEY` on every backend.

Give every replica and every deployment the same key. A server with a
different key rejects the sessions that the other servers issued.
```

Set `REFLEX_SECRET_KEY` to a random value of at least 32 bytes. Store it in
your deployment's secret manager or environment. Never put it in
`rxconfig.py`, and keep any `.env` file that holds it out of version control.
To generate a key:

```bash
python -c "import secrets; print(secrets.token_hex(32))"
```

Without `REFLEX_SECRET_KEY`, `reflex run` generates a temporary key and logs a
warning. All sessions reset when `reflex run` restarts. A backend started
another way, such as by an ASGI server with several workers, generates a key
in each worker, and the workers reject each other's sessions.

### Changing the key

```md alert warning
# Keep the old key when you add a new one.

If you replace the old key with the new key, every session resets at once.
```

1. Put the new key first and the old key after it, separated by a comma:
`REFLEX_SECRET_KEY=<new key>,<old key>`. Restart every backend.
2. Wait at least `session_token_max_age`. Active sessions move to the new key
as their cookies renew.
3. Remove the old key: `REFLEX_SECRET_KEY=<new key>`, and restart every
backend.

If the old key leaked, set only the new key at once. Every session resets, and
cookies signed with the leaked key stop working.

## Origins, cookies, and embedding

- Set `api_url` to the public backend URL, including when TLS terminates at a
reverse proxy.
- Apps on the same host must have different `app_name` values, because
cookies are not scoped by port.
- The frontend gets its session cookie only from an origin that the backend
trusts: the backend's own origin, `deploy_url`, `api_url`, explicit
`cors_allowed_origins`, and the local development origins.
`cors_allowed_origins=["*"]` does not count. List the host origins of an
EmbedPlugin explicitly.
- Browsers store the cookie only over HTTPS or on `localhost`. A production
app served over plain HTTP on another host has no session cookie, so under
`enforce` every new connection starts with fresh state. In development on
another host, set `api_url` to the address that the browser uses.
- Cross-site iframes keep their session in browsers that support partitioned
cookies. The session belongs to the top-level site.

The session cookie is removed from request headers before they reach app code.
Use `rx.Cookie` for cookies that browser JavaScript must read.

## Server-side state access

`EventContext.session_token` holds the validated `SessionToken` of the event,
with a non-secret `id`, `issued_at`, `expires_at`, and
`authorizes(client_token)`. It does not mean that the client is logged in.

`app.modify_state`, event enqueueing, and chained events use the session of
the current event or request. Under `enforce`, a handler cannot change the
state of another session, or link an `rx.SharedState` to a client token that
another session owns.

Lifespan tasks run with `SessionToken.SYSTEM`. For trusted server-side
fan-out, pass it explicitly:

```python
from reflex_base.session import SessionToken

async with app.modify_state(
rx.BaseStateToken(ident=client_token, cls=MyState),
session_token=SessionToken.SYSTEM,
) as root_state:
state = await root_state.get_state(MyState)
state.message = "Server maintenance starts soon"
```

Never use `SYSTEM` for a client token that a request supplies. A custom
endpoint that calls the state manager directly must do its own authorization.
Rate-limit `/_reflex/session` in your reverse proxy or `api_transformer`.

## Clients that are not browsers

To create a session, send a JSON `POST` with an empty object to
`/_reflex/session` (under `backend_path`, if you set one). The response sets
the session cookie and returns `client_token`, `expires_in`, and `refresh_in`.
Send that cookie and client token on later requests. To keep an existing
client token, send it in the `Reflex-Client-Token` header.

## Troubleshooting

**Every reload starts with fresh state.** The browser has no session cookie.
Check that your proxy forwards `/_reflex/session`, that the app is served over
HTTPS, and that the frontend origin is trusted (see
[Origins, cookies, and embedding](#origins-cookies-and-embedding)).

**All tabs lose their state after a restart or deploy.** `REFLEX_SECRET_KEY`
is not set, or the backends do not share it.

**The browser console says the backend does not trust the origin.** Add that
origin to `deploy_url` or `cors_allowed_origins`.

**Uploads return 403.** The session expired or the browser has no session
cookie. Reload the page; if that does not help, see the first item.

**Server code raises `SessionAuthorizationError`.** It changes the state of
another session. Pass `session_token=SessionToken.SYSTEM` if the code is
trusted.
20 changes: 20 additions & 0 deletions docs/app/tests/conftest.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
"""Shared fixtures for the docs app tests."""

from collections.abc import Generator

import pytest


@pytest.fixture(autouse=True)
def _session_token_compatibility_mode() -> Generator[None, None, None]:
"""Run the tests in the session mode that allows tokens without a session.

The example tests address state with a plain token and no browser session,
which the default enforce mode rejects.

Yields:
Control while the mode is set.
"""
with pytest.MonkeyPatch.context() as patch:
patch.setenv("REFLEX_SESSION_TOKEN_MODE", "warn")
yield
18 changes: 15 additions & 3 deletions docs/hosting/self-hosting.md
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,8 @@ reflex run --env prod
```

Production mode compiles the app, builds an optimized static frontend, and
serves it together with the backend (event websocket, `/ping`, `/_upload`)
serves it together with the backend (event websocket, `/ping`, `/_upload`,
`/_reflex/session`)
from a single server on port `3000`. Pass `--frontend-port` or
`--backend-port` to listen on a different port. When redis is configured,
the server runs up to 8 backend workers by default (`2 * cpu_count + 1`, capped at 8).
Expand All @@ -54,6 +55,15 @@ seconds, it stops the server. Set `GRANIAN_RESPAWN_FAILED_WORKERS=false` to stop
server when any worker dies instead, for example when a process supervisor restarts it.
Only the worker's exit is logged by default; set `GRANIAN_LOG_LEVEL=info` to see the respawn too.

Set `REFLEX_SECRET_KEY` to the same random value on every backend, and keep it
across deploys. It signs the browser session cookies. Without it, each
`reflex run` generates a temporary key, so all browser sessions and their state
reset on every restart, and servers with different keys reject each other's
sessions. A backend started another way, for example by an ASGI server that
runs several workers, generates a key in each worker, so its own workers
reject each other's sessions. See
[browser sessions](/docs/api-routes/sessions/#signing-keys).

When using Granian on Linux, backend workers are forked from a supervisor
process that has already imported the app, so they share its memory instead of
each importing the app again. Set `REFLEX_BACKEND_START_METHOD=spawn` (or
Expand All @@ -77,7 +87,8 @@ REFLEX_API_URL=http://localhost:8000 reflex run --env prod --frontend-only --fro
```

Alternatively, put a reverse proxy in front of both processes and route the
backend routes (`/_event`, `/ping`, `/_upload`, `/_health`) to the backend
backend routes (`/_event`, `/ping`, `/_upload`, `/_health`, `/_reflex/session`)
Comment thread
FarhanAliRaza marked this conversation as resolved.
Resolved
to the backend
port, as the `Caddyfile`s in the container examples below do.

Instances of Reflex 0.9 and 0.10 cannot share a state store, whether Redis or
Expand Down Expand Up @@ -124,7 +135,8 @@ time or export time to retain the default for local development.
If you want to serve the backend behind a reverse proxy at a subpath (e.g.
nginx routing `/api/*` to Reflex), set `backend_path` on the config instead of
baking the prefix into `api_url`. Every backend endpoint (event websocket,
`/ping`, `/_upload`, `/_health`, `/_all_routes`) is mounted under that prefix,
`/ping`, `/_upload`, `/_health`, `/_reflex/session`, `/_all_routes`) is mounted
under that prefix,
and the frontend baked into the export automatically calls the backend at the
prefixed URLs — no request rewriting in the proxy is required.

Expand Down
2 changes: 1 addition & 1 deletion news/+browser-session-transport.feature.md
Original file line number Diff line number Diff line change
@@ -1 +1 @@
Add browser sessions using HttpOnly cookies and a `POST /_reflex/session` endpoint that issues a client token bound to the requesting session. Sessions scope HTTP and custom WebSocket state access; authenticated sockets can renew their cookie credentials without losing client state.
Add browser sessions using HttpOnly cookies and a `POST /_reflex/session` endpoint that issues a client token bound to the requesting session. Sessions scope HTTP and custom WebSocket state access; authenticated sockets can renew their cookie credentials without losing client state. See the [browser sessions guide](https://reflex.dev/docs/api-routes/sessions/) for configuration and migration.
1 change: 1 addition & 0 deletions news/+session-harness.bugfix.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
AppHarness now points the development frontend at `localhost` for the backend API, so browser cookies remain same-site during tests.
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Session ownership is enforced by default. State access needs the browser session that owns the client token: `app.modify_state` and event enqueueing raise `SessionAuthorizationError` for a token that the session does not own, and unauthorized uploads return HTTP 403. Trusted server-side code passes `session_token=SessionToken.SYSTEM`. A tab that presents an unowned token gets a new token and fresh state. Keep the default: `REFLEX_SESSION_TOKEN_MODE=warn` or `off` turns this protection off and is only an escape hatch for a deployment that breaks before its code is fixed. Before you deploy, set `REFLEX_SECRET_KEY` on every backend and route `/_reflex/session` to the backend in your reverse proxy: without them, state resets on each restart or reload. See the [browser sessions guide](https://reflex.dev/docs/api-routes/sessions/).
Comment thread
FarhanAliRaza marked this conversation as resolved.
Resolved

This file was deleted.

Original file line number Diff line number Diff line change
@@ -1 +1 @@
Establish browser sessions over the WebSocket while hydration begins, then persist them through HTTP-only cookies with automatic refresh. New routing-token and freshness keys are scoped to each backend URL. Idle tabs renew their session cookies automatically; transient cookie-exchange failures retry without blocking WebSocket events, and queued uploads remain cancellable.
Establish browser sessions over the WebSocket while hydration begins, then persist them through HTTP-only cookies with automatic refresh. New routing-token and freshness keys are scoped to each backend URL. Idle tabs renew their session cookies automatically; transient cookie-exchange failures retry without blocking WebSocket events, and queued uploads remain cancellable. See the [browser sessions guide](https://reflex.dev/docs/api-routes/sessions/) for configuration and migration.
2 changes: 1 addition & 1 deletion packages/reflex-base/src/reflex_base/environment.py
Original file line number Diff line number Diff line change
Expand Up @@ -808,7 +808,7 @@ class EnvironmentVariables:

# Rollout mode for session-bound client tokens.
REFLEX_SESSION_TOKEN_MODE: EnvVar[Literal["off", "warn", "enforce"]] = env_var(
"warn"
"enforce"
)

# Whether to keep React's development-build owner-stack capture in dev mode.
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
File uploads carry the browser session cookie, and an upload for a client token that the session does not own returns HTTP 403. Keep the default `enforce` mode: `REFLEX_SESSION_TOKEN_MODE=warn` or `off` turns the rejection off and is only an escape hatch. See the [browser session guide](https://reflex.dev/docs/api-routes/sessions/) for configuration and migration.
14 changes: 9 additions & 5 deletions reflex/testing.py
Original file line number Diff line number Diff line change
Expand Up @@ -396,9 +396,8 @@ def _start_frontend(self):
with chdir(self.app_path):
config = get_config()
print("Polling for servers...") # for pytest diagnosis #noqa: T201
config.api_url = "http://{}:{}".format(
*self._poll_for_servers(timeout=30).getsockname(),
)
# Match the dev frontend's hostname so browser cookies are same-site.
config.api_url = f"http://localhost:{self._poll_for_servers(timeout=30).getsockname()[1]}"
print("Building frontend...") # for pytest diagnosis #noqa: T201
reflex.utils.build.setup_frontend(self.app_path)

Expand Down Expand Up @@ -918,7 +917,12 @@ def _wait_frontend(self):
) + config.prepend_frontend_path("/")
config.deploy_url = self.frontend_url

def _start_backend(self):
def _start_backend(self, port: int = 0):
"""Start a production backend with its worker settings on the requested port.

Args:
port: Backend port, or zero to choose an available port.
"""
if self.app_asgi is None:
msg = "App was not initialized."
raise RuntimeError(msg)
Expand All @@ -928,7 +932,7 @@ def _start_backend(self):
uvicorn.Config(
app=self.app_asgi,
host="127.0.0.1",
port=0,
port=port,
workers=reflex.utils.processes.get_num_workers(),
),
)
Expand Down
Loading
Loading