Opinionated rules and patterns for building high-quality, cross-platform mobile apps with TypeScript/React Native and Dart/Flutter, covering architecture, coding style, error handling, testing, performance, security, CI/CD and DevSecOps.
Finally, a comprehensive ruleset that eliminates the constant decision fatigue and configuration headaches that plague modern mobile development. These Cursor Rules transform your development workflow from reactive troubleshooting to proactive, predictable delivery.
You know the drill. Your team spends more time configuring toolchains, debugging platform-specific quirks, and maintaining inconsistent code patterns than actually building features. Security vulnerabilities slip through manual reviews. Performance bottlenecks emerge in production. CI/CD pipelines break when someone updates a dependency.
The cost? Delayed releases, frustrated users, and development teams burning out on infrastructure instead of innovation.
These Cursor Rules establish a complete, opinionated development ecosystem that handles the complex decisions so you don't have to. From TypeScript configuration to CI/CD automation, from security patterns to performance optimization – everything is pre-configured based on battle-tested practices from successful mobile teams.
What you get:
// Inconsistent error handling across components
const UserProfile = () => {
const [user, setUser] = useState(null);
const [loading, setLoading] = useState(true);
useEffect(() => {
fetchUser().then(setUser).catch(console.error);
setLoading(false);
}, []);
return loading ? <Spinner /> : <UserDetails user={user} />;
};
// Standardized error handling with cancellation
const UserProfile = () => {
const { data: user, loading, error } = useSafeAsync(
() => userService.getProfile(),
[]
);
if (loading) return <Spinner />;
if (error) return <ErrorBoundary error={error} />;
return <UserDetails user={user} />;
};
Stop debugging production crashes from unhandled promises. The rules establish discriminated union error types that surface meaningful information:
type AppError =
| { type: 'NETWORK'; message: string; retryable: true }
| { type: 'BUSINESS'; message: string; retryable: false }
| { type: 'FATAL'; message: string; retryable: false };
Automatically enforce certificate pinning, secure storage, and biometric authentication without manual configuration:
// Automatic secure storage with biometric fallback
const credentials = await secureStorage.get('user_token', {
requireBiometric: true,
fallbackToPasscode: true
});
Built-in caching strategies, lazy loading patterns, and memory management that maintains 60fps animations:
// Automatic image caching with MMKV
const OptimizedImage = ({ uri }) => (
<CachedImage
source={{ uri }}
cacheKey={generateCacheKey(uri)}
loadingComponent={<ImageSkeleton />}
/>
);
# Copy the rules to your Cursor configuration
cp mobile-dev-rules.json ~/.cursor/rules/
The rules automatically scaffold the recommended folder structure:
app/
├── atoms/ # Reusable UI components
├── molecules/ # Compound components
├── organisms/ # Complex UI patterns
├── screens/ # Screen-level components
├── navigation/ # Route configuration
├── hooks/ # Custom React hooks
├── state/ # Global state management
├── services/ # API and external services
└── utils/ # Helper functions
// tsconfig.json (auto-generated)
{
"compilerOptions": {
"strict": true,
"noUncheckedIndexedAccess": true,
"exactOptionalPropertyTypes": true
}
}
The rules include GitHub Actions workflows for:
"We went from spending 30% of our time on configuration and debugging to focusing entirely on features. The error handling patterns alone saved us weeks of production firefighting." - Senior Mobile Developer
These Cursor Rules eliminate the complexity that's been holding your team back. Stop reinventing the wheel for every project. Start with a foundation that's already proven in production environments.
Your mobile apps deserve better than ad-hoc patterns and configuration drift. Make the switch to systematic, predictable mobile development that scales with your team.
The rules are comprehensive, battle-tested, and ready to implement. Your next mobile release will be your smoothest yet.
You are an expert in cross-platform mobile development using TypeScript + React Native, Dart + Flutter, Kotlin (Android), Swift (iOS), GraphQL/REST back-ends, CI/CD, DevSecOps and cloud services (Firebase, AWS, GCP).
Key Principles
- Start from business goals → measurable app KPIs (retention, crash-free sessions, conversion).
- Mobile-first thinking: design for thumb reach, variable connectivity, battery & memory limits.
- Component-based UI and micro-service back-end; isolate domain logic from presentation.
- Security is non-negotiable: adopt zero-trust, least privilege, privacy-by-design.
- Automate everything (CI/CD), ship small increments, monitor, and iterate via analytics & A/B tests.
- One source of truth per concern (state, theme, strings, keys). Avoid duplication.
- Prefer declarative, functional style; minimise shared mutable state.
- Fail fast: validate inputs early, exit early on error, keep happy path obvious.
- Keep dependencies up-to-date; prefer well-maintained, minimal packages.
- Write code that is self-documenting; comments only for WHY, not WHAT.
TypeScript / JavaScript Rules
- Enable `strict`, `noUncheckedIndexedAccess`, `exactOptionalPropertyTypes` in tsconfig.
- File naming: kebab-case.tsx for React Native components, snake_case.test.ts for tests.
- Export single default React component per file; related hooks & types in same folder.
- Interfaces over type aliases for public contracts; use `type` for utility unions/intersections.
- Destructure props & params; mark unused variables with leading underscore.
- Avoid `any`; fallback is `unknown` + type-guard.
- Use async/await; never mix `.then()` after `await`.
- Linting: eslint-airbnb-types with prettier; 100 col limit; single quotes; trailing commas.
Dart / Flutter Rules
- Use null-safety everywhere (`late` only when constructor guarantees init).
- Prefer `const` widgets; extract widgets when tree depth > 3.
- File naming: snake_case.dart, folders using snake_case.
- Build UIs with `Widgets` not `Functions` if stateful; use `HookWidget`/`Riverpod` for state.
- Keep build methods < 40 lines; offload calculations to `compute()` for isolates.
- Default immutability: use `freezed` for data classes, `equatable` for comparison.
Kotlin (Android) Rules
- Use Kotlin + Coroutines + Flow; avoid `LiveData` where Flow suffices.
- Leverage Jetpack Compose; @Composable functions < 50 lines.
- Strict nullability; enable `-Xexplicit-api=strict`.
Swift (iOS) Rules
- Swift 5.9+, enable strict concurrency (`@MainActor`, `Sendable`).
- Use SwiftUI; View structs must remain value-types; limit body to 40 lines.
Error Handling & Validation
- Validate user input, API payloads, and device capabilities upfront.
- In React Native: create `useSafeAsync(fn)` that wraps promises with try/catch and cancellation token (to avoid setState on unmounted component).
- Domain-level errors use discriminated union (`{type: 'NETWORK' | 'BUSINESS' | 'FATAL'; message: string}`) and bubble up.
- Log unexpected errors to Sentry/Firebase Crashlytics with context (user id, device, app version) but NEVER PII.
- Display user-friendly messages mapped from error type; always provide offline fallback if possible.
React Native Framework Rules
- Only functional components + hooks. Ban `class` components by ESLint.
- Navigation: use React Navigation v6; type all route params.
- State management: prefer Zustand or Recoil; avoid global Redux unless complex cross-screen flows.
- Styling: Tailwind-RN (twrnc) or StyleSheet + design-token theme; disallow inline literal colors.
- Performance: enable Hermes; wrap heavy lists with `FlashList` or `RecyclerListView`.
- Gestures: react-native-gesture-handler + Reanimated 3 for 60fps animations.
- Permissions via `react-native-permissions`; check → prompt → act flow.
Flutter Framework Rules
- State: Riverpod 2 (code-gen) or Bloc if complex; avoid setState in large widgets.
- Routing: go_router with deep-link support.
- Theme.dart holds color tokens, typography, spacing; reference via `Theme.of`.
- Internationalisation: flutter_gen + arb files; require locale test.
- Android/iOS integration: write platform channels in Kotlin/Swift; keep UI logic in Dart.
Testing
- Pyramid: 70% unit, 20% widget, 10% E2E.
- TypeScript: vitest + react-native-testing-library; mock native modules with `jest.mock`.
- Dart: `flutter test`, golden tests for widgets, `integration_test` package for E2E.
- Automated device lab: run on Firebase Test Lab + BrowserStack.
- Enforce 90% line & branch coverage gates in CI.
Performance & Optimisation
- Lazy-load screens via dynamic import (RN) / deferred components (Flutter).
- Cache API & images with SWR + MMKV (RN) / `flutter_cache_manager`.
- Monitor TTI, FPS, memory; budget: cold start < 2 s, frame drop < 1%.
- Use profiler (Flipper, Dart DevTools) each sprint to regress.
Security
- Adopt DevSecOps: SAST (CodeQL), DAST (OWASP ZAP), dependency scanning (Renovate).
- Use Keychain/Keystore via secure storage libs; never persist tokens plain.
- Enable certificate pinning; HTTPS only.
- Enforce biometric auth for sensitive flows; fallback secure passcode.
- Obfuscate (ProGuard/R8) & symbol strip; enable Apple Privacy Manifest.
CI/CD
- GitHub Actions → build matrix (iOS, Android) with reusable workflows.
- Steps: lint → test → build → static analysis → sign → upload to TestFlight/Play Internal.
- Semantic versioning via conventional commits; auto-release notes.
- Canary rollout 5% users; automatic rollback on crash-free < 99%.
Analytics & Feedback
- Use Firebase Analytics + Amplitude; track funnels tied to KPIs.
- Feature flags (LaunchDarkly) for A/B tests; evaluate via stats toolkit.
- In-app NPS prompt post-success event.
Accessibility
- Minimum 4.5:1 contrast; dynamic type, VoiceOver/TalkBack labels.
- RN: `accessibilityRole`, `accessibilityLabel`; Flutter: `Semantics` widget.
- Run axe-android/ios & flutter_a11y in CI.
Folder Structure (RN example)
```
app/
atoms/ # 1-screen reusable ui pieces
molecules/
organisms/
screens/
navigation/
hooks/
state/
services/ # api, auth, storage
utils/
test/
```
Common Pitfalls & Guards
- Abort fetch on component unmount → custom hook.
- Keep SDK versions aligned; mismatch causes build flakiness.
- Push notifications: handle notification-tap cold start route.
- Handle low-memory/low-battery events.
- Validate store listing assets & privacy labels during CI to prevent release rejection.