Designing a cloud file storage frontend with resumable uploads, virtualized file browser, sharing and permissions, preview system, real-time sync, and offline support.
FrontendX EngineeringSystem Design Series #9
0. What Are We Building?
A Google Drive-like cloud file storage application where users upload, organize, preview, and share files and folders. The product lets users browse a folder tree, drag-and-drop files from their desktop, preview images and documents inline, share items with configurable permissions, and see changes from other users in real time.
Think Google Drive, Dropbox, or OneDrive. These are not simple file listings — they are desktop-class applications running in the browser. A folder with 10,000 items must render instantly. A 2 GB video upload must survive a network disconnect. A shared folder with 50 collaborators must show the right permission for every file without leaking data.
Key Insight
Cloud file storage is one of the hardest frontend engineering challenges because it combines a virtualized file browser (thousands of rows), a resumable upload engine (chunked, multi-part, with pause/resume), a real-time sync layer (WebSocket + polling), and a permission system with inheritance rules complex enough that Google Drive's own API docs have dedicated pages for edge cases. Every major product handles these differently, and those differences are visible in your DevTools.
We will focus on the core web application: the file browser, upload engine, sharing system, preview pipeline, and real-time sync. Mobile apps, desktop sync clients, and the backend storage pipeline are outside scope.
1. Requirements & Scoping
Before writing any code, we define what we are building. A cloud storage app is vast, so scoping is critical.
Functional
Browse folders and files with grid/list toggle view
Upload files of any size with visible per-file progress
Offline support via service worker for recently viewed items
Tip
The MVP for a cloud storage app is: upload a file, see it in a list, open it, and share it. Version history, trash, search, and real-time sync are all v2 features — but designing for them from the start prevents painful architectural rewrites later.
2. Architecture & High-Level Design
The architecture of a cloud file storage frontend is fundamentally different from a content site or e-commerce store. File listings are private and behind authentication — there is no SEO argument for SSR. But performance still matters deeply: users open Dropbox on slow office WiFi and expect the folder to appear quickly, not after three sequential round trips.
Rendering Strategy: CSR SPA with SSR Shell
Google Drive uses Web Components (built with Lit) running as a fully client-side application. The HTML source shows a minimal shell with custom element tags — the rows are painted by JavaScript after the page loads. Dropbox, by contrast, spent years on a Python server-rendered system called DWS before migrating to Edison, a Node.js-based SSR system where gRPC calls initiate during the server-side React render and stream results into the HTML response before the client JavaScript asks for them.
For our design, we use a hybrid: server-render the application shell and stream initial data alongside the HTML, then hand off to CSR for all subsequent interactions. The file listing page uses React Server Components for the initial render and hydration, while all folder navigation after that is client-side. This gives us the fastest possible initial paint without committing to server-rendering every folder view.
SSR vs CSR for Cloud Storage
example.typescript
┌─────────────────────────────────┬─────────────┬──────────────┐
│ │ SSR Shell │ Full CSR │
│ │ + CSR SPA │ (Drive) │
├─────────────────────────────────┼─────────────┼──────────────┤
│ First paint │ Instant │ Slight delay│
│ Folder-to-folder nav │ Client │ Client │
│ │ side │ side │
│ Initial data in HTML │ Yes │ No │
│ Service worker caching │ Yes │ Yes │
│ Server cost │ Low │ Minimal │
│ Bundle size on first load │ Smaller │ Larger │
│ │ (shell+ │ (full app) │
│ │ routes) │ │
└─────────────────────────────────┴─────────────┴──────────────┘
State Management
We separate server state (API data — file lists, folder metadata, sharing permissions) from UI state (which rows are selected, whether the upload tray is open, modal visibility). For server state we use TanStack Query, which handles caching, background refetching, and loading states without manually managing cache keys. For UI state we use React's built-in useState and useReducer— no global store needed.
Note
The anti-pattern to avoid is running everything through a single Redux-Saga middleware chain. In a file storage frontend, the upload queue, the notification system, the sharing modal, and the folder view all need to react to state changes independently. Keeping these concerns in separate local states synchronized through TanStack Query's shared cache is significantly cleaner.
Component Tree
The application is split into four top-level regions that never re-render as a group. Each region owns its own state and communicates with others through events or the shared cache.
example.typescript
AppShell
├── NavigationSidebar ← folder tree, starred, shared-with-me, trash, storage meter
├── Toolbar ← search bar, upload button, view toggle (list/grid), sort menu
├── MainContent ← current view (folder, search results, shared, recent)
│ ├── FileListView ← virtualized list or grid of DriveItem rows/cards
│ │ └── FileRow / FileCard (per item)
│ └── PreviewPanel ← lazy-loaded; overlays the list when a file is selected
└── UploadTray ← fixed bottom bar showing active upload queue with progress bars
The NavigationSidebar and UploadTray are always mounted. The MainContent swaps its content based on the active route but never unmounts entirely, preserving scroll position. The PreviewPanel is a React lazy import — its JavaScript is not downloaded until the first time the user clicks a file.
Routing
example.typescript
/drive → My Drive root
/drive/folders/:folderId → Folder view (deep links work)
/drive/shared → Shared with me
/drive/recent → Recently opened
/drive/trash → Trash / deleted items
/drive/search?q=:query → Search results
/drive/file/:fileId/preview → Inline preview (parallel route)
/s/:shareToken → Public shared link landing page
The preview route is a Next.js parallel route — the folder view stays visible behind the preview panel. This is the same pattern Dropbox uses for its lightbox-style media viewer.
System architecture — CSR SPA with SSR shell, normalized TanStack Query cache shared across sidebar and main content, resumable upload engine, WebSocket real-time sync
A file storage app has more entities than meets the eye. The data model spans files, folders, permissions, versions, upload jobs, and activity entries. Getting these right upfront avoids painful migrations later.
DriveItem — File and Folder Entity
example.typescript
interface DriveItem {
id: string;
name: string;
type: "file" | "folder";
mimeType: string;
size: number; // Bytes — 0 for folders
createdAt: string;
modifiedAt: string;
modifiedBy: UserRef;
parentId: string | null; // null for root
path: string[]; // Ancestor IDs from root to parent (for breadcrumbs)
isStarred: boolean;
isTrashed: boolean;
trashedAt: string | null;
thumbnailUrl: string | null;
downloadUrl: string | null; // Signed URL with short expiry
// Permission data for the currently authenticated user
myRole: "owner" | "editor" | "commenter" | "viewer" | null;
sharingInfo: SharingInfo | null;
version: number; // Monotonically increasing for conflict detection
// Client-only fields — never from the server:
isSelectedByMe: boolean;
uploadStatus: UploadStatus | null;
uploadProgress: number | null;
}
The inheritedFrom field is critical. When the sharing modal opens for a file, some collaborators got access through a parent folder. Google Drive's API is explicit: inherited permissions cannot be removed or reduced on a child item. The "Remove" button for inherited collaborators must be disabled with a tooltip explaining why, pointing to the parent folder's sharing settings.
All items are stored in a flat itemsById map inside TanStack Query's cache. Folder children are stored as ordered arrays of IDs. This normalization means a single cache update propagates to every subscribed component — sidebar, breadcrumbs, and file list — without explicit communication between them.
The API layer defines how the frontend talks to the backend. For a file storage app, we need REST endpoints for CRUD operations, a chunked upload protocol, and a WebSocket for real-time sync.
REST Endpoints
example.typescript
── Folder & File CRUD ──────────────────────────
GET /api/drive/folders/:folderId/children
?pageSize=50&cursor=:cursor&sortBy=name|modified|size&sortOrder=asc|desc
→ { items: DriveItem[], nextCursor: string | null, totalCount: number }
── Search ─────────────────────────────────────
GET /api/drive/search?q=:query&mimeType=:filter&owner=me|anyone
→ { items: DriveItem[], nextCursor: string | null }
── Upload (files > 5 MB use chunked) ──────────
POST /api/drive/upload/session
{ name, parentId, mimeType, size }
→ { sessionId: string, chunkSize: number }
PUT /api/drive/upload/session/:sessionId/chunk
headers: Content-Range: bytes {start}-{end}/{totalSize}
body: Blob
→ 200 OK { bytesReceived: number }
→ 201 Created { item: DriveItem } ← final chunk only
── Sharing ────────────────────────────────────
GET /api/drive/items/:itemId/sharing
→ { collaborators, sharedLinks, generalAccess, inheritedCollaborators }
POST /api/drive/items/:itemId/links
{ role, password?, expiresAt?, allowDownload? }
→ { link: SharedLink }
── Delta Sync ─────────────────────────────────
GET /api/drive/sync/delta?cursor=:syncCursor&folderId=:folderId
→ { changes: DeltaChange[], nextCursor: string }
── WebSocket ──────────────────────────────────
{ event: "file_changed", folderId, itemId, version }
{ event: "sharing_changed", itemId }
Delta Sync Protocol
The WebSocket event does not send the full file object — only the ID and new version number. When the client receives this message it checks its cached itemsById[itemId].version. If the versions differ, it fires a targeted GET /api/drive/items/:itemIdto fetch the latest metadata. This keeps WebSocket payloads small and avoids broadcasting large objects to all connected users.
Note
We do not keep the WebSocket open on backgrounded tabs. When document.visibilityState becomes "hidden", we close the WebSocket and switch to polling at 60-second intervals. When the tab becomes visible again, we reconnect, send the stored syncCursor, and apply the delta of all changes that happened while backgrounded.
Optimistic Updates
Every mutation — rename, move, delete, share — follows the same optimistic pattern: update the cache immediately, send the API call in the background, and roll back the cache if the call fails.
example.typescript
async function renameItem(itemId: string, newName: string) {
const previousItem = queryClient.getQueryData<DriveItem>(["item", itemId]);
// Optimistic update
queryClient.setQueryData<DriveItem>(["item", itemId], (old) =>
old ? { ...old, name: newName } : old
);
try {
await api.renameItem(itemId, newName);
} catch (error) {
// Rollback
queryClient.setQueryData<DriveItem>(["item", itemId], previousItem);
showError("Could not rename this item.");
}
}
Key Insight
Both the FolderTreeItem in the sidebar and the FileRow in the main content area call useQuery({ queryKey: ["item", itemId], ... }). When setQueryData updates the cache entry, React re-renders both components automatically. This is how we synchronize the sidebar and main content without any global store.
Component Contracts
Components like FileRow and SharingModal receive everything through props:
The file browser is the central view of the application. It needs to handle folders with thousands of items, support grid and list views, drag-and-drop, multi-select with keyboard modifiers, and inline rename — all without performance degradation.
Virtualized File List
The single biggest performance problem in a file browser is rendering large folders. If a user's folder has 10,000 items, rendering all 10,000 DOM nodes at once will freeze the browser for several seconds. The fix is to render only the items currently visible in the viewport, plus a small buffer above and below.
We use TanStack Virtual to calculate which rows are visible given the current scroll offset and render only those. Items that scroll out of view are removed from the DOM — their space is held by empty padding elements so the scroll bar behaves correctly.
The file list supports three multi-select patterns: Click + Ctrl/Cmd toggles individual files; Click + Shift selects a contiguous range; Ctrl+A selects all loaded items in the current folder.
Right-clicking a file row opens a floating menu positioned at the cursor using floating-ui for viewport edge detection. Menu items vary based on item type, user role, and selection count.
Pressing F2 on a selected file activates inline rename. The file name text becomes an <input> element in place, pre-populated with the current name and the text selected. Enter commits the change, Escape cancels. We apply optimistic updates — the name updates immediately while the API call runs in the background.
Folder Tree Sidebar
The left sidebar shows a recursive folder tree with lazy loading at each level — a folder's children are only fetched when it is expanded. The sidebar highlights the currently active folder and auto-expands ancestors using the path array on the active item.
example.typescript
interface FolderTreeState {
expandedFolderIds: Set<string>;
loadedChildrenByFolderId: Record<string, string[]>;
loadingFolderIds: Set<string>;
}
// Auto-expand ancestors of the active folder
useEffect(() => {
if (!activeFolderId) return;
const activeItem = itemsById[activeFolderId];
if (!activeItem) return;
activeItem.path.forEach((ancestorId) => {
dispatch({ type: "EXPAND", folderId: ancestorId });
});
}, [activeFolderId]);
Drag-and-Drop
Drag event handling is attached directly to documentvia a custom hook. The critical insight is an enter counterrather than a boolean. Every time the cursor moves from a parent to a child, the browser fires dragleave on the parent and dragenter on the child. Without the counter, the overlay flickers. The counter increments on every dragenterand decrements on every dragleave — the canvas is only exited when the counter hits zero.
For folder drops from the desktop, we use DataTransferItem.webkitGetAsEntry(). The FileSystemDirectoryReader.readEntries() spec caps each call at 100 entries — we loop until the batch is empty to avoid silently dropping files.
6. Upload Engine
The upload engine is the most technically challenging part of the frontend. It must handle files of any size, survive network failures, show accurate progress, and not block the UI.
Upload job state machine — queued → hashing → session creation → uploading (3 parallel chunks) → committing → complete, with pause/resume and retry with exponential backoff
Chunked, Resumable Uploads
Uploading a 2 GB video file as a single HTTP request will fail on most home connections — a network hiccup at minute 18 means starting from zero. We split every file larger than 5 MB into chunks and upload them in parallel batches of 3.
We limit active uploads to 3 at a time. More than 3 concurrent large uploads saturates a typical home internet connection. Within each upload, we send up to 3 chunks in parallel — this means up to 9 simultaneous HTTP requests, appropriate for fast broadband without being aggressive.
Retry with Exponential Backoff
When a chunk fails with a network error, we retry with exponential backoff before marking the job as failed: 1s, 2s, 4s, 8s, 16s. After 5 failed attempts, the job transitions to "error" status. The "retrying" status causes the upload tray row to show "Retrying…" and the progress bar stops animating forward.
Resume After Page Refresh
When a page refresh or browser crash interrupts an upload, we check IndexedDB for any pending sessions on app boot. If found, we show a resume banner: "report.mp4 was interrupted. Pick up where you left off?"
We ask the server how many bytes it has already received via GET /api/drive/upload/session/:sessionId/status. The progress bar for a resumed upload does not start at 0 — it starts at whatever percentage the server has already received. If a 1 GB file was 60% uploaded before the refresh, the progress bar opens at 60%.
Upload Tray
The upload tray is a fixed bar at the bottom of the screen. It is always mounted so it can show in-progress uploads while the user navigates between folders. It has two modes: collapsed (a compact bar showing a summary) and expanded (a panel showing each file individually with progress bars, pause/resume, and retry buttons).
example.typescript
// The tray header changes what it shows based on active jobs:
function TrayHeaderContent({ activeCount, failedCount, completedCount, overallProgress }) {
if (activeCount > 0) {
return <>Uploading {activeCount} file{activeCount !== 1 ? "s" : ""}…</>;
}
if (failedCount > 0) {
return <>{failedCount} upload{failedCount !== 1 ? "s" : ""} failed</>;
}
return <>{completedCount} upload{completedCount !== 1 ? "s" : ""} complete</>;
}
Speed Calculation
Upload speed ("1.2 MB/s") is calculated by tracking the timestamp of the last chunk completion and comparing it to the bytes uploaded since then. We sample speed after each batch of 3 parallel chunks rather than after every single chunk, to avoid jitter from fast chunks completing out of order.
Key Insight
The progress bar uses an indeterminate shimmer animation during the "hashing" and "creating-session" phases — phases where we do not have a real progress percentage yet. Once the actual upload starts and chunks begin completing, the bar snaps to the real percentage and the animation stops. This is the same pattern Google Drive uses for its upload progress.
7. Preview System
The preview panel is one of the most visible parts of the product. Getting it right requires handling a wide range of file types, loading states, and navigation patterns without ever making the user download a file they only wanted to glance at.
Preview Routes
There are two routes where a preview is shown. The overlay previewis a parallel-route panel that slides in from the right when the user clicks a file in the list, occupying roughly 60% of the viewport while the folder list shrinks to 40%. The standalone preview page at /drive/file/:fileId is used when arriving via a notification email link or shared file link.
Preview Types
example.typescript
type PreviewRenderer =
| "image" // JPEG, PNG, GIF, WebP, SVG — progressive loading
| "pdf" // Browser's built-in PDF viewer via <embed>
| "video" // Native <video> element
| "audio" // Native <audio> element
| "text" // Syntax-highlighted code viewer (TXT, MD, JSON, JS, TS, PY)
| "office" // DOCX, XLSX, PPTX — server-side conversion to PDF
| "google-doc" // Google Docs/Sheets/Slides — embedded via iframe
| "unsupported"; // File icon + download button
function getPreviewRenderer(mimeType: string): PreviewRenderer {
if (mimeType.startsWith("image/")) return "image";
if (mimeType === "application/pdf") return "pdf";
if (mimeType.startsWith("video/")) return "video";
if (mimeType.startsWith("audio/")) return "audio";
if (mimeType.startsWith("text/") ||
["application/json", "application/javascript",
"application/typescript"].includes(mimeType)) return "text";
if (["application/vnd.openxmlformats-officedocument"
".wordprocessingml.document",
"application/vnd.openxmlformats-officedocument"
".spreadsheetml.sheet",
"application/vnd.openxmlformats-officedocument"
".presentationml.presentation"].includes(mimeType))
return "office";
if (mimeType.startsWith("application/vnd.google-apps."))
return "google-doc";
return "unsupported";
}
Progressive Image Loading
For image previews, we load a low-resolution thumbnail immediately (already available from the file list) and replace it with the full-resolution image once it loads. The thumbnail stays blurred until the full image loads, then fades in over 300ms — the same technique Google Images and Unsplash use.
Office Document Preview
DOCX, XLSX, and PPTX files cannot be rendered natively in the browser. We handle these with a two-step approach: the server converts them to PDF on-demand and returns a signed URL. The frontend renders the PDF using the browser's built-in PDF viewer via an <iframe> with a sandbox attribute to prevent JavaScript execution in the preview context.
Preview Navigation
The overlay preview includes left and right arrow buttons to step through files in the current folder without going back to the list. Navigation uses the folderChildren array from the normalized state — we find the current file's index and move forward or backward. Left and Right arrow keys step through files; Escape closes the panel and returns focus to the file row that was open.
8. Sharing & Permissions
Sharing is the most complex feature in any cloud storage frontend. It looks simple on the surface — a modal with a text field and a dropdown — but underneath it is a layered permission system with inheritance rules, multiple link types, expiry controls, and edge cases that can expose private data if implemented incorrectly.
Permission inheritance — folder permissions cascade to all children; inherited permissions show as disabled in the sharing modal; direct permissions can upgrade but not downgrade
The Permission Model
Google Drive uses four roles: Viewer (read-only), Commenter (read and comment), Editor (read, write, and comment), and Owner (full control including permanent deletion and ownership transfer). We implement the same model.
When a folder is shared with someone, all files and sub-folders inside it automatically inherit the same permission level. The inheritance rule propagates downward: permission lists for a folder cascade through all nested children. Inherited permissions can be upgraded on a child item (giving a user higher access to a specific file), but they cannot be downgraded. If a user has Editor access on the parent folder, you cannot make them a Viewer on a single file inside it.
This directly affects the sharing UI. When the modal opens for a file, we must distinguish between direct collaborators and inherited collaborators. Inherited collaborators show an "Inherited from [Folder Name]" sublabel, and the "Remove access" button is disabled with a tooltip explaining why.
The Sharing Modal — State Machine
The sharing modal has five distinct states, driven by a useReducer:
The modal opens in "loading", fetches sharing data, and transitions to "overview". Clicking "Add people" goes to "invite". Clicking the gear icon next to a link opens "link-settings" as a slide-in panel with a CSS transform: translateX transition.
Inviting Collaborators
The people picker is a combobox that searches for users as the user types. Two sources of suggestions: users within your organization and recent collaborators. We debounce the API call at 300ms and support multiple invites in a single send — the user types email addresses, presses Enter or comma to add each as a tag, and picks the role once for the whole batch.
example.typescript
// The collaborators list inside the sharing modal shows three groups:
// 1. Owner — always at top, role read-only, no remove button
// 2. Direct collaborators — role dropdown enabled, remove available
// 3. Inherited collaborators — "Inherited from [Folder]" sublabel, remove disabled
function CollaboratorRow({ collaborator, onRoleChange, onRemove, currentUserId }) {
const isOwner = collaborator.role === "owner";
const isInherited = collaborator.inheritedFrom !== null;
const canEdit = !isOwner && !isInherited;
return (
<div className="collaborator-row">
<Avatar src={collaborator.avatarUrl} name={collaborator.displayName} size={32} />
<div className="collaborator-info">
<span>{collaborator.displayName}</span>
<span>{collaborator.email}</span>
{isInherited && (
<button onClick={() => navigateToParentFolder(collaborator.inheritedFrom!)}>
Inherited from {getParentFolderName(collaborator.inheritedFrom!)}
</button>
)}
</div>
{canEdit ? (
<RoleDropdown value={collaborator.role} onChange={(r) => onRoleChange(userId, r)}
includeRemoveOption />
) : (
<Tooltip content="Access inherited from parent folder">
<InfoIcon />
</Tooltip>
)}
</div>
);
}
Shared Links
Every item can have two distinct shareable links: a view-only link and an edit link. Each has its own password, expiry date, and download toggle. The link settings panel within the sharing modal lets users set a password (minimum 8 characters, complexity requirement), an expiry date (minimum tomorrow, expires at 11:59 PM in the creator's timezone), and a download toggle (disabled for non-previewable MIME types).
General Access
The "General access" control has three options: Restricted (only explicit collaborators), Anyone with the link (public — shows a one-time confirmation warning), and Anyone in the organization (signed-in users in your org).
Folder Sharing — Propagation
Sharing a folder with thousands of files requires a background propagation job on the server. We handle this with a three-phase flow: optimistic update (appears immediately with "Pending" badge), background propagation (server walks the tree), and propagation complete (WebSocket event removes badge).
Revoking Access — Retained Access Problem
Removing a collaborator from a folder has a subtle complication: if any files inside that folder were shared directly with this user (not through folder inheritance), those direct permissions are not removed. We surface this in the revocation confirmation dialog: "Alex will lose access to this folder and 47 files inside it. Alex also has direct access to 2 files that will NOT be affected."
Transfer of Ownership
Transferring ownership is a significant action. The dropdown shows "Transfer ownership" below a divider, with a dedicated confirmation modal explaining what is lost. Dropbox documents that transferring ownership of a folder does not transfer ownership of the shared links created by the original owner — we surface this in the confirmation message.
The Shared Link Landing Page
When a recipient clicks a shared link, they land on /s/:shareToken — a page outside the authenticated drive shell. The server resolves the token and checks the link's access settings. If expired, the page shows "This link has expired." If a password is required, a password form appears before any content.
Restoring a version creates a new version at the top of the history (the restored content becomes the new current version) rather than removing history. This is how both Google Drive and Dropbox handle it — the history stays intact so you can always see what was changed and when.
Trash and Recovery
Deleted items stay in trash for 30 days before permanent auto-deletion. The trash view looks identical to the regular folder view but with "Date deleted" and "Original location" columns. Soft delete vs permanent delete: moving to trash marks the file as deleted (content remains on server); "Delete forever" permanently removes content. We show a strong confirmation dialog for permanent deletion: "This cannot be undone."
If a user trashes a folder and then a file inside it, and then tries to restore the file, the original parent no longer exists. We handle this by restoring the file to the drive root with a notice: "The original folder was deleted. This file was restored to My Drive."
10. Performance Optimization
Performance is the defining characteristic of a cloud file storage app. Every millisecond of latency in the file browser is perceived by the user as the app being "slow." Here are the techniques that matter most.
Technique 1: Virtualized File List
Render only the items visible in the viewport using TanStack Virtual. With overscan of 5 rows, a folder with 10,000 items renders ~30 DOM nodes instead of 10,000. This is the single biggest performance win — without it, the app is unusable for power users.
All items live in a flat itemsById map in TanStack Query's cache. Mutations update the cache immediately and roll back on failure. The sidebar and main content both subscribe to the same cache keys, so changes propagate instantly without any event system.
Technique 3: Lazy-Loaded Thumbnails
Thumbnails are loaded lazily using IntersectionObserver. Opening a folder with 500 photos does not fire 500 simultaneous image requests; it fires only for images currently in the viewport, with a 200px root margin for pre-loading.
A user browsing their files downloads none of these until they actually trigger them. Dropbox replaced their custom bundler with Rollup and gained a 33% reduction in bundle size — their old bundler had a 6,000+ line manually maintained module dictionary with no tree shaking.
Technique 5: Thumbnail CDN
Thumbnail generation happens on the server at upload time. The thumbnailUrl field points to the nearest CDN edge node for the requesting user's geography. Images are served as WebP with responsive sizing via URL parameters.
Technique 6: Performance Measurement
Standard metrics like LCP do not capture folder-to-folder navigation — a navigation does not trigger a new LCP measurement. Dropbox built and open-sourced @dropbox/ttvc, a library measuring Time To Visually Complete (TTVC): the moment all pixels in the viewport stop changing, using MutationObserver and IntersectionObserver.
Technique 7: IndexedDB Caching for Offline
We use Workbox to set up a service worker with different caching strategies for different request types. The app shell uses stale-while-revalidate. API responses for folder listings use network-first with a 3-second timeout and cache fallback. Thumbnails use cache-first with an LRU limit of 500 entries and 7-day expiry.
Technique 8: Offline Write Queue
When the user is offline and attempts to rename, move, or create a folder, we queue the mutation in IndexedDB and show a toast: "You're offline. Changes will sync when you reconnect." When the browser fires the online event, we replay all queued mutations.
Key Insight
The performance hierarchy for cloud storage: (1) Virtualized file list is non-negotiable — without it, power users cannot use the product. (2) Normalized cache with optimistic updates makes every interaction feel instant. (3) Bundle splitting keeps the initial load fast. (4) CDN thumbnails and service worker caching make subsequent visits feel native. Do them in this order.
11. Security
Cloud file storage deals with sensitive user data — personal documents, financial records, internal company files. A security breach here is catastrophic.
Never Trust the Client-Side Role
The myRole field drives which UI buttons appear, but all authorization decisions are made server-side. If a user manipulates their client-side role to "owner", the Share button may appear, but the API returns 403 Forbidden. We document this explicitly in the codebase.
example.typescript
// NOTE: myRole controls UI elements shown, but the server
// re-validates authorization on every mutation. Never skip the server check.
const canShare = item.myRole === "owner";
const canEdit = item.myRole === "owner" || item.myRole === "editor";
Shared Link Tokens Are Credentials
The shareToken in /s/:shareToken is a credential — whoever has the URL has the access. We exclude share token routes from analytics pageview tracking and set Referrer-Policy: no-referrer on shared link pages so the token is not exposed in the Referer header.
Content Security Policy for Preview Iframe
Office document previews render converted PDF content inside an <iframe>. Without protection, a malicious DOCX could execute JavaScript. We prevent this with the sandbox attribute: allow-same-origin only — no scripts, no forms.
Rate Limiting the People Picker
The people picker fires an API call on each keypress (debounced to 300ms). This endpoint queries the organization's user directory, which could expose email addresses at scale. We add server-side rate limiting at 60 requests per minute per authenticated user. If exceeded, the endpoint returns 429 Too Many Requests and the frontend shows the field in an errored state.
XSS in Filenames
Filenames are user-generated content. A file named <script>alert(1)</script>.pdf must not execute JavaScript when rendered in the file list. We sanitize all filename rendering using React's built-in JSX escaping (which handles this automatically) and never use dangerouslySetInnerHTML with filenames.
Warning
Never log share tokens to analytics pipelines, error reporting services, or browser history. The shared link page route (/s/:shareToken) should be excluded from analytics pageview tracking. Share tokens are credentials, and leaking them to third-party services is a security incident.
12. Testing Strategy
Testing a cloud file storage app means testing user flows — not just components. The sharing module receives the most thorough test coverage because it involves the most complex logic and the highest cost of a bug.
Unit Tests: Pure Logic
Cover all pure logic functions: checkMoveConflicts,getContextMenuItems,getPreviewRenderer,formatActivityAction, the sharingModalReducer,getNextToStart for the upload queue, anduseSearchSuggestions. These tests run in under 50ms each and cover edge cases exhaustively.
example.typescript
describe("checkMoveConflicts", () => {
it("returns empty for a file with no sharing", () => {
const result = checkMoveConflicts(privateFile, "folderA", folderB);
expect(result).toEqual([]);
});
it("returns conflicts when inherited collaborators are not in destination", () => {
const result = checkMoveConflicts(sharedFile, "folderA", privateFolder);
expect(result).toHaveLength(3);
expect(result[0].willLoseAccess).toBe(true);
});
it("does not flag inherited collaborators also present in destination", () => {
const result = checkMoveConflicts(sharedFile, "folderA", alsoSharedFolder);
expect(result).toHaveLength(0);
});
});
Component Tests: Sharing Modal States
Render the sharing modal with @testing-library/react and mock the API client. Key test cases:
Loading state shows skeleton UI, not empty modal
Inherited collaborators show the "Inherited from" sublabel and disabled remove button
Direct collaborators show a role dropdown and "Remove access" option
"Transfer ownership" appears only for owner-level direct collaborators
Toggling "Require password" shows and hides the password input
The "Allow download" toggle is disabled for non-previewable MIME types
Switching general access to "Anyone with the link" triggers a confirmation dialog
E2E Tests: Full User Flows
Playwright tests running against a staging environment:
Sign in as User A, upload a file, share it, invite User B as Editor
Sign in as User B, verify the file appears in "Shared with me", edit it
Sign in as User A, change User B's role to Viewer, verify edit button is disabled
Create a shareable view link, open in incognito, verify preview without sign-in
Add a password to the link, verify password form appears, test correct and incorrect passwords
Visual Regression Tests
Capture screenshots of the sharing modal, the file row with different sharing indicators, and the shared link landing page. Any pixel-level change fails the build and requires engineer review. This catches accidental CSS changes that affect permission visuals.
Tip
The sharing modal is the most tested component because a permission bug is a security incident. Every PR that touches the sharing module must pass the full E2E sharing suite. These tests run in CI on every pull request and take approximately 4 minutes on a parallel test runner with 4 workers.
13. Accessibility
Cloud file storage accessibility is about enabling power users who rely on the keyboard to navigate files as fast as mouse users.
ARIA Roles for the File List
The file list is a complex composite widget. We expose it as role="grid" with each row as role="row" and each cell as role="gridcell". Screen readers announce the file name, type, size, and modification date for each row.
Keyboard Navigation
example.typescript
// Supported keyboard shortcuts:
// Key Action
// Enter Open the selected file or folder
// F2 Inline rename
// Delete Move to trash
// Ctrl+A Select all loaded items
// Ctrl+Z Undo last move or rename
// Escape Clear selection / close preview
// Arrow keys Navigate through items
Undo Stack
We implement undo as a client-side undo stack. Each destructive operation pushes a record containing enough information to reverse the action. After a trash operation, a toast appears: "3 items moved to trash. [Undo]". The undo stack holds the last 10 operations and clears on page refresh.
Modal Focus Management
The sharing modal uses role="dialog" with aria-modal="true" and a focus trap — when the modal opens, focus moves to the first interactive element, Tab cycles through modal controls only, and focus returns to the "Share" button when the modal closes.
Upload Tray ARIA
The upload tray uses role="region" with aria-label="Upload queue" and aria-live="polite". Each progress bar has role="progressbar" with aria-valuenow, aria-valuemin, and aria-valuemax so screen readers announce upload progress as it changes.
People Picker Combobox
The people picker follows the ARIA combobox pattern: role="combobox" on the input, role="listbox" on the suggestions panel, role="option" on each suggestion. Arrow keys navigate the list, Enter selects, Escape collapses.
Focus indicators: Every interactive element has a visible focus ring (2px outline with 3px offset)
Reduced motion: Respect prefers-reduced-motion for upload progress animations and modal transitions
Tip
Test the complete file browsing flow with a screen reader (VoiceOver on Mac, NVDA on Windows). If a user cannot navigate from the folder list to a file, open its preview, share it with someone, and return to the list using only the keyboard, your accessibility has a gap. Fix it before shipping.
14. Key Takeaways
Building a cloud file storage frontend taught me that this is not a CRUD app with file icons — it is a desktop-class application that happens to run in a browser. Every design decision affects how users perceive speed and reliability. Here is what I wish I knew before starting:
Virtualization is non-negotiable
Without virtualized rows, a folder with 10,000 items freezes the browser for seconds. TanStack Virtual is the first dependency you should install.
Optimistic updates with normalized cache
Update the cache immediately, roll back on failure. Both the sidebar and main content subscribe to the same cache keys — no event system needed.
Chunked uploads with exponential backoff
Files larger than 5 MB are split into chunks, uploaded in parallel batches of 3. Each chunk retries 5 times with exponential backoff. The progress bar survives page refreshes.
Permission inheritance is harder than it looks
Inherited permissions cannot be downgraded on children. The sharing modal must distinguish direct from inherited collaborators, disable remove for inherited, and link to the parent folder's settings.
WebSocket + polling hybrid for real-time sync
Keep the WebSocket open on active tabs, switch to 60-second polling on background tabs. WebSocket events carry only the item ID and version — the full fetch happens on demand.
Client-side role is UI-only — authorize on the server
myRole drives which buttons appear, but every API call re-validates authorization. Never trust the client for permission decisions.