{"record":{"id":"e9aa2f960d899889","repo":"DioxusLabs/dioxus","slug":"failed-to-serialize-sse-event","errorCode":null,"errorMessage":"Failed to serialize SSE event","messagePattern":"Failed to serialize SSE event","errorType":"panic","errorClass":null,"httpStatus":null,"severity":"error","filePath":"packages/fullstack/src/payloads/sse.rs","lineNumber":318,"sourceCode":"\n            Self {\n                _marker: std::marker::PhantomData,\n                client: None,\n                keep_alive: Some(KeepAlive::new().interval(Duration::from_secs(15))),\n                sse: Some(sse),\n            }\n        }\n\n        /// Create a `ServerEvents` from a `TryStream` of events.\n        pub fn from_stream<S>(stream: S) -> Self\n        where\n            S: TryStream<Ok = T, Error = BoxError> + Send + 'static,\n            T: Serialize,\n        {\n            let stream = stream.map_ok(|event| {\n                axum::response::sse::Event::default()\n                    .json_data(event)\n                    .expect(\"Failed to serialize SSE event\")\n            });\n            let sse = axum::response::Sse::new(stream.boxed());\n            Self {\n                _marker: std::marker::PhantomData,\n                client: None,\n                keep_alive: Some(KeepAlive::new().interval(Duration::from_secs(15))),\n                sse: Some(sse),\n            }\n        }\n\n        /// Set the keep-alive configuration for the SSE connection.\n        ///\n        /// A `None` value will disable the default `KeepAlive` of 15 seconds.\n        pub fn with_keep_alive(mut self, keep_alive: Option<KeepAlive>) -> Self {\n            self.keep_alive = keep_alive;\n            self\n        }\n","sourceCodeStart":300,"sourceCodeEnd":336,"githubUrl":"https://github.com/DioxusLabs/dioxus/blob/393d190a801ccb441d41923e232289b4f8a5c669/packages/fullstack/src/payloads/sse.rs#L300-L336","documentation":"ServerEvents::from_stream maps every item of the user's TryStream through axum's Event::json_data. json_data returns Err when serde_json cannot serialize the event (custom Serialize impls that fail, maps with non-string keys, invalid nested payloads) and the closure unwraps it with expect, so one bad event panics the stream task.","triggerScenarios":"Streaming a type T through ServerEvents::from_stream where T's Serialize errors at runtime: HashMap<u32, _> or other non-string-keyed maps, hand-written Serialize impls returning Err, or types that encode invalid JSON in edge cases.","commonSituations":"Server-function SSE endpoints returning dynamic/aggregate payloads; switching an event struct to a map keyed by numeric ids; custom Serialize impls that can fail on edge-case state.","solutions":["Fix the event type: use string keys (HashMap<String, _>, BTreeMap) and derive Serialize where possible","Pre-test representative events with serde_json::to_string before wiring them into the stream","For dynamic payloads, send pre-serialized JSON via ServerEvents::new + SseTx instead of from_stream","Add unit tests that serialize every event variant the stream can emit"],"exampleFix":"// before\nlet events = ServerEvents::from_stream(\n    stream.map_ok(|ev: HashMap<u32, String>| ev), // non-string keys -> serde_json error\n);\n// after\nlet events = ServerEvents::from_stream(\n    stream.map_ok(|ev: HashMap<String, String>| ev),\n);","handlingStrategy":"validation","validationCode":"// Smoke-test the event type before wiring the stream:\nfn can_serialize<T: Serialize>(event: &T) -> bool {\n    serde_json::to_string(event).is_ok()\n}\nassert!(can_serialize(&sample_event));","typeGuard":null,"tryCatchPattern":"// Send pre-serialized events via SseTx, handling failures explicitly:\nServerEvents::new(move |tx| async move {\n    while let Some(ev) = rx.next().await {\n        match serde_json::to_string(&ev) {\n            Ok(json) => { tx.send(json); }\n            Err(e) => { tracing::error!(\"skipping unserializable event: {e}\"); }\n        }\n    }\n})","preventionTips":["Derive Serialize on event types instead of hand-written impls","Use string keys in maps sent over SSE","Add serialization round-trip tests for every event variant","For dynamic payloads, stream pre-serialized strings instead of typed values"],"tags":["sse","serialization","serde","fullstack","streaming","panic"],"backgroundTag":null,"analyzedSha":"393d190a801ccb441d41923e232289b4f8a5c669","analyzedAt":"2026-08-16T11:27:45.815Z","schemaVersion":2},"datasetVersion":"2026-08-16T13:17:31.715Z"}