D
Flutter WebMedium30 XP4 min read

How do you use localStorage and cookies in Flutter Web?

TL;DR: Use shared_preferences plugin (which uses localStorage on web) for non-sensitive data. Never store auth tokens in localStorage — vulnerable to XSS. Use HttpOnly cookies (server-set) for tokens: JavaScript cannot read them, immune to XSS attacks.

Full Answer

AspectStorageCharacteristics
localStorage5-10MB, persistent, JS-readableNon-sensitive prefs, theme, settings
sessionStorage5MB, cleared on tab closeTemporary session data
Cookie4KB, sent with requests, expiryAuth tokens (HttpOnly+Secure)
IndexedDBGBs, async, structuredOffline data, large datasets
⚠️

NEVER store auth tokens in localStorage. Any XSS vulnerability can steal them. HttpOnly cookies are invisible to JavaScript — server sets them, browser sends them automatically, JavaScript cannot access them.

Code Examples

dartshared_preferences for cross-platform storage
Output
// shared_preferences: one API for all platforms
// localStorage: JS-readable, not for secrets
// HttpOnly cookie: XSS-safe, server-set only

Common Mistakes

  • Storing JWT in localStorage — stolen by any XSS injection. Use HttpOnly cookies instead
  • Using dart:html directly in cross-platform code — fails to compile for mobile

Interview Tip

💡

localStorage vs HttpOnly cookies for auth tokens is a classic security question. Explain: HttpOnly = JavaScript cannot read it, Secure = HTTPS only, SameSite=Strict = CSRF protection. This trio makes auth cookies safe.

#localStorage#cookies#web-storage#persistence#security