{"id":"61bc419d8118f4e0","repo":"gofiber/fiber","slug":"csrf-failed-to-store-token-in-storage-w","errorCode":null,"errorMessage":"csrf: failed to store token in storage: %w","messagePattern":"csrf: failed to store token in storage: %w","errorType":"http","errorClass":null,"httpStatus":null,"severity":"error","filePath":"middleware/csrf/csrf.go","lineNumber":283,"sourceCode":"func getRawFromStorage(c fiber.Ctx, token string, cfg *Config, sessionManager *sessionManager, storageManager *storageManager) ([]byte, error) {\n\tif cfg.Session != nil {\n\t\treturn sessionManager.getRaw(c, token, dummyValue), nil\n\t}\n\traw, err := storageManager.getRaw(c, token)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"csrf: failed to fetch token from storage: %w\", err)\n\t}\n\treturn raw, nil\n}\n\n// createOrExtendTokenInStorage creates or extends the token in the storage\nfunc createOrExtendTokenInStorage(c fiber.Ctx, token string, cfg *Config, sessionManager *sessionManager, storageManager *storageManager) error {\n\tif cfg.Session != nil {\n\t\tsessionManager.setRaw(c, token, dummyValue, cfg.IdleTimeout)\n\t\treturn nil\n\t}\n\tif err := storageManager.setRaw(c, token, dummyValue, cfg.IdleTimeout); err != nil {\n\t\treturn fmt.Errorf(\"csrf: failed to store token in storage: %w\", err)\n\t}\n\treturn nil\n}\n\nfunc deleteTokenFromStorage(c fiber.Ctx, token string, cfg *Config, sessionManager *sessionManager, storageManager *storageManager) error {\n\tif cfg.Session != nil {\n\t\tsessionManager.delRaw(c)\n\t\treturn nil\n\t}\n\tif err := storageManager.delRaw(c, token); err != nil {\n\t\treturn fmt.Errorf(\"csrf: failed to delete token from storage: %w\", err)\n\t}\n\treturn nil\n}\n\n// Update CSRF cookie\n// if expireCookie is true, the cookie will expire immediately\nfunc updateCSRFCookie(c fiber.Ctx, cfg *Config, token string) {","sourceCodeStart":265,"sourceCodeEnd":301,"githubUrl":"https://github.com/gofiber/fiber/blob/9a4c7e57fe0b080a04235d28a4b0d2b4b353d58c/middleware/csrf/csrf.go#L265-L301","documentation":"Thrown at middleware/csrf/csrf.go:283 by createOrExtendTokenInStorage() when storageManager.setRaw fails while writing (or refreshing) the CSRF token. Every safe-method request and every validated unsafe request writes/extends a token, so a Storage SET failure surfaces here.","triggerScenarios":"The CSRF middleware generates a fresh token (or extends an existing one) and calls storageManager.setRaw -> Storage.SetWithContext, which fails: backend OOM, connection lost, ctx cancelled, disk full.","commonSituations":"Redis maxmemory-policy returning errors under load; persistent backend out of disk; storage AUTH expired; client disconnect mid-request causing ctx cancellation during SET.","solutions":["Identify and resolve the backend write refusal from the wrapped driver error.","Ensure the storage backend has enough capacity for the IdleTimeout-bounded token set.","Set the storage write timeout below the request deadline so SETs complete before ctx cancellation.","Configure cfg.ErrorHandler to return 503 with retry semantics so the client retries cleanly.","If writes routinely fail, consider cfg.Session to piggyback on the session store's write path with its own retry/resilience."],"exampleFix":"// before\napp.Use(csrf.New(csrf.Config{ Storage: redis.New() }))\n\n// after: explicit IdleTimeout + tolerant error handler\napp.Use(csrf.New(csrf.Config{\n    Storage:     redis.New(),\n    IdleTimeout: 30 * time.Minute,\n    ErrorHandler: func(c fiber.Ctx, err error) error {\n        if strings.Contains(err.Error(), \"failed to store token\") {\n            return c.Status(fiber.StatusServiceUnavailable).\n                SendString(\"token store unavailable; please retry\")\n        }\n        return c.Status(fiber.StatusForbidden).SendString(err.Error())\n    },\n}))","handlingStrategy":"try-catch","validationCode":"// At boot, validate the CSRF store accepts writes.\nctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)\ndefer cancel()\nif err := store.SetWithContext(ctx, \"__csrf_probe__\", []byte(\"+\"), time.Minute); err != nil {\n    log.Fatalf(\"csrf storage write probe failed: %v\", err)\n}","typeGuard":null,"tryCatchPattern":"cfg.ErrorHandler = func(c fiber.Ctx, err error) error {\n    if strings.Contains(err.Error(), \"failed to store token\") {\n        c.Set(fiber.HeaderRetryAfter, \"5\")\n        return c.Status(fiber.StatusServiceUnavailable).\n            SendString(\"token store busy; retry shortly\")\n    }\n    return c.Status(fiber.StatusForbidden).SendString(err.Error())\n}","preventionTips":["Probe write capability at startup.","Size storage for the IdleTimeout-bounded token working set.","Tune the storage write timeout below the request deadline.","Return 503 + Retry-After so clients retry cleanly on transient failures."],"tags":["csrf","storage","network","security","fiber"],"analyzedSha":"9a4c7e57fe0b080a04235d28a4b0d2b4b353d58c","analyzedAt":"2026-08-04T21:44:03.395Z","schemaVersion":2}