{"record":{"id":"4ca824aa3fbf868a","repo":"gofiber/fiber","slug":"failed-to-encode-data-w","errorCode":null,"errorMessage":"failed to encode data: %w","messagePattern":"failed to encode data: %w","errorType":"exception","errorClass":null,"httpStatus":null,"severity":"error","filePath":"middleware/session/session.go","lineNumber":399,"sourceCode":"\t}\n\n\ts.mu.Lock()\n\tdefer s.mu.Unlock()\n\n\t// Set idleTimeout if not already set\n\tif s.idleTimeout <= 0 {\n\t\ts.idleTimeout = s.config.IdleTimeout\n\t}\n\n\t// Update client cookie\n\ts.setSession()\n\n\t// Encode session data\n\ts.data.RLock()\n\tencodedBytes, err := s.encodeSessionData()\n\ts.data.RUnlock()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to encode data: %w\", err)\n\t}\n\n\t// Pass copied bytes with session id to provider\n\treturn s.config.Storage.SetWithContext(ctx, s.id, encodedBytes, s.idleTimeout)\n}\n\n// Keys retrieves all keys in the current session.\n//\n// Returns:\n//   - []any: A slice of all keys in the session.\n//\n// Usage:\n//\n//\tkeys := s.Keys()\nfunc (s *Session) Keys() []any {\n\tif s.data == nil {\n\t\treturn []any{}\n\t}","sourceCodeStart":381,"sourceCodeEnd":417,"githubUrl":"https://github.com/gofiber/fiber/blob/a105acad6c1e4576a77f01e02973f67e962bb58d/middleware/session/session.go#L381-L417","documentation":"Thrown by saveSessionWithContext when the session's in-memory data map cannot be gob-encoded before being written to the Storage backend. The %w wraps the underlying gob.Encoder error, which names the offending type or value. This is the top-level error a caller of Save()/saveSessionWithContext observes; the sibling error 202 is the same root cause surfaced from the lower-level encodeSessionData.","triggerScenarios":"Calling session.Save() (or relying on the middleware's auto-save) while s.data.Data holds a value gob cannot encode: a channel, func, complex64/128, an interface{} whose concrete type was not registered with gob.Register, a struct containing such fields, or a value with a cycle gob refuses.","commonSituations":"Storing a custom struct in the session without calling gob.Register at init; storing map[string]any with arbitrarily-typed values whose concrete types gob does not know about; storing closures/callbacks; upgrading Fiber and storing newly-typed values without registering them.","solutions":["Inspect the wrapped error — gob names the unencodable type (e.g. gob: type not registered for interface: main.Foo).","Call gob.Register(YourType{}) in an init() for every custom struct stored in the session.","Avoid storing channels, funcs, complex numbers, or unregistered interface values; store primitive/serializable representations instead.","If you must store dynamic types, wrap them in a concrete registered struct."],"exampleFix":"// before\nsess.Set(\"user\", User{Name: \"x\", Conn: someChan})\nsess.Save() // -> failed to encode data: gob: unsupported type\n\n// after (init)\nfunc init() { gob.Register(User{}) }","handlingStrategy":"validation","validationCode":"// Run before storing custom types in the session.\nfunc registerSessionTypes() {\n    gob.Register(MyStruct{})\n    gob.Register(&MyStruct{})\n    gob.Register(map[string]any{})\n}\nfunc isGobEncodable(v any) error {\n    switch reflect.TypeOf(v).Kind() {\n    case reflect.Chan, reflect.Func, reflect.Complex64, reflect.Complex128, reflect.UnsafePointer:\n        return fmt.Errorf(\"type %T is not gob-encodable\", v)\n    }\n    return nil\n}","typeGuard":"func isStorableInSession(v any) bool {\n    if v == nil { return true }\n    switch reflect.TypeOf(v).Kind() {\n    case reflect.Chan, reflect.Func, reflect.Complex64, reflect.Complex128:\n        return false\n    }\n    return true\n}","tryCatchPattern":"if err := sess.Save(); err != nil {\n    // a failed encode usually means a bad value type; log and drop the value\n    log.Printf(\"session save failed: %v\", err)\n    sess.Destroy()\n}","preventionTips":["gob.Register every custom struct type at program init, before any session is touched.","Never store channels, funcs, or complex numbers in the session.","Prefer storing simple structs / primitives rather than map[string]any with dynamic concrete types.","Add a unit test that round-trips every value type you intend to store through gob encode+decode."],"tags":["session","serialization","gob","encoding"],"backgroundTag":null,"analyzedSha":"a105acad6c1e4576a77f01e02973f67e962bb58d","analyzedAt":"2026-08-11T17:33:26.942Z","contentChangedAt":null,"schemaVersion":2},"datasetVersion":"2026-09-23T08:17:48.524Z"}