How the FastAPI Python Sidecar Communicates with the GeoLibre Frontend: A Complete Guide
The GeoLibre frontend communicates with its FastAPI Python sidecar through a token-authenticated HTTP client in packages/processing/src/sidecar-client.ts, using automatic URL resolution, per-launch authentication tokens, and strict CORS/host protection.
GeoLibre is an open-source geospatial processing platform built by opengeos that bridges web-based UI components with high-performance Python geoprocessing tools. The architecture relies on a FastAPI Python sidecar that runs alongside the frontend—either as a spawned subprocess in Tauri desktop builds or as a containerized service in Docker deployments. This article explains exactly how the two sides establish secure, reliable communication based on the actual source code implementation.
URL Resolution: Direct Localhost vs. Reverse Proxy
The first step in any sidecar request is determining where to send it. The resolveSidecarBaseUrl() function in packages/processing/src/sidecar-client.ts (lines 16-42) implements a three-tier resolution strategy:
- Tauri desktop or Vite dev server: Uses
http://127.0.0.1:8765(LOCAL_SIDECAR_URL) - Docker/web deployments: Routes through same-origin proxy at
/<origin>/sidecar - Custom overrides: Respects
VITE_SIDECAR_URLenvironment variable
// packages/processing/src/sidecar-client.ts
import { resolveSidecarBaseUrl } from "./sidecar-client";
const sidecarBase = resolveSidecarBaseUrl();
// → "http://127.0.0.1:8765" (desktop) or "/sidecar" (Docker)
The reverse proxy approach eliminates CORS complications by ensuring all requests appear same-origin to the browser. This is configured in the Docker/Nginx layer, not in application code.
Authentication: Per-Launch Tokens and Secure Headers
Security relies on a per-launch secret token generated when the desktop shell spawns the sidecar.
Token Flow
- Generation: Tauri backend calls
start_geolibre_sidecar()and creates a random secret - Storage: Frontend receives token via Tauri command and stores it with
setSidecarAuthToken() - Transmission:
sidecarFetch()wrapper injectsX-GeoLibre-Tokenheader on every request - Validation: FastAPI middleware in
backend/geolibre_server/geolibre_server/app/main.py(lines 58-84) verifies the token
// packages/processing/src/sidecar-client.ts
import { setSidecarAuthToken, sidecarFetch } from "./sidecar-client";
// Store token received from Tauri backend
setSidecarAuthToken("my-launch-secret");
// All subsequent requests include X-GeoLibre-Token header
const response = await sidecarFetch(`${baseUrl}/health`);
The sidecar also accepts Authorization: Bearer <token> as an alternative header format. In browser/Docker builds, the proxy automatically injects the token, so the client leaves headers untouched.
The Request Flow: From Frontend to FastAPI Endpoints
All sidecar communication flows through typed helper functions that wrap sidecarFetch(). The codebase exposes endpoints for health checks, algorithm discovery, Whitebox geoprocessing, raster/vector operations, and format conversion.
Health Check Example
// packages/processing/src/sidecar-client.ts
export async function checkSidecarHealth(
baseUrl = DEFAULT_SIDECAR_URL,
): Promise<SidecarHealth | null> {
const res = await sidecarFetch(`${baseUrl}/health`);
return res.ok ? await res.json() : null;
}
// Usage
import { checkSidecarHealth } from "./sidecar-client";
const health = await checkSidecarHealth(); // {status: "ok"}
Whitebox Tool Execution
import { fetchWhiteboxTools, runWhiteboxTool } from "./sidecar-client";
// Discover available tools
const tools = await fetchWhiteboxTools(); // [{id: "reproject_vector", ...}, ...]
// Execute with job-based async processing
const job = await runWhiteboxTool({
tool_id: "reproject_vector",
parameters: {
src: "input.geojson",
dst_epsg: 3857
},
});
// Returns job descriptor for polling via /whitebox/jobs/:id
The same pattern applies to /algorithms, /whitebox/run, /whitebox/jobs/:id, and /whitebox/output endpoints defined in backend/geolibre_server/geolibre_server/app/whitebox.py.
Security Layers: CORS and Host Protection
The GeoLibre sidecar implements defense in depth against cross-origin attacks through two mechanisms:
FastAPI Middleware Layer
backend/geolibre_server/geolibre_server/app/main.py configures:
TrustedHostMiddleware: ValidatesHostheader against allowlist- CORS middleware: Restricts origins to Tauri webview and
http://localhost:5173
Reverse Proxy Layer
Docker/Nginx configuration adds same-origin routing that prevents direct external access to the sidecar port.
This double-layer architecture means:
- Malicious websites cannot reach
localhost:8765directly (blocked by CORS) - Even with CORS bypassed, invalid
Hostheaders are rejected - Docker deployments never expose the sidecar port externally
Data Exchange Formats
The FastAPI Python sidecar returns structured data in two modes:
| Data Type | Format | Endpoint Pattern |
|---|---|---|
| Status, catalogs, job metadata | JSON | /health, /algorithms, /whitebox/jobs/:id |
| Large binary outputs (rasters, vectors) | Raw bytes or JSON description | /whitebox/output with vector_output_format parameter |
For geospatial outputs, the frontend requests the output endpoint and receives either a direct byte stream or a JSON-encoded file reference depending on the requested format.
Key Source Files
| Component | File Path | Purpose |
|---|---|---|
| Sidecar client library | packages/processing/src/sidecar-client.ts |
URL resolution, token storage, fetch wrappers |
| Base URL resolver | lines 16-42 of above | Environment-aware endpoint selection |
| Token & fetch handling | lines 46-80 of above | Authentication injection |
| FastAPI entry point | backend/geolibre_server/geolibre_server/app/main.py |
Router mounting, middleware configuration |
| Authentication middleware | lines 58-84 of above | Token validation logic |
| Whitebox API router | backend/geolibre_server/geolibre_server/app/whitebox.py |
Geoprocessing endpoints |
Summary
resolveSidecarBaseUrl()automatically selects between direct localhost and same-origin proxy pathssetSidecarAuthToken()andsidecarFetch()implement per-launch authentication viaX-GeoLibre-Tokenheader- All endpoints use typed wrappers that centralize error handling and response parsing
- Dual security layers (CORS +
TrustedHostMiddleware) prevent cross-origin abuse while supporting flexible deployments - Data exchange uses JSON for metadata and binary streams for large geospatial outputs
The opengeos/GeoLibre implementation demonstrates a production-ready pattern for bridging desktop/web frontends with Python backend services.
Frequently Asked Questions
Does the GeoLibre sidecar use WebSockets or HTTP for communication?
The FastAPI Python sidecar uses standard HTTP/REST, not WebSockets. Long-running geoprocessing jobs use an async job pattern: POST /whitebox/run returns a job ID, and the frontend polls GET /whitebox/jobs/:id until completion. This simplifies proxy configuration and retries.
How does the sidecar authentication work in Docker deployments?
In Docker builds, the reverse proxy automatically injects the authentication token. The frontend client detects the proxy environment (via origin detection in resolveSidecarBaseUrl()) and omits the X-GeoLibre-Token header. The proxy adds it before forwarding to the sidecar, keeping secrets out of browser-visible code.
Can I run the GeoLibre sidecar on a custom port or remote host?
Yes. Set the VITE_SIDECAR_URL environment variable before building or running the frontend. This overrides the automatic resolution in resolveSidecarBaseUrl(). For production deployments, use the reverse proxy approach to avoid CORS configuration entirely.
What prevents malicious websites from accessing my local sidecar?
Three protections: (1) CORS policy in FastAPI rejects requests from unknown origins; (2) TrustedHostMiddleware validates the Host header; (3) the per-launch token is unpredictable and never exposed to arbitrary JavaScript contexts. These layers prevent DNS rebinding and cross-site request attacks.
Have a question about this repo?
These articles cover the highlights, but your codebase questions are specific. Give your agent direct access to the source. Share this with your agent to get started:
curl -s "https://instagit.com/install.md" Maintain an open-source project? Get it listed too →