Actionable Rules for building ultra-fast, highly-resilient front-end applications with modern JS/TS frameworks and tooling.
Transform every millisecond of your user experience into competitive advantage. These Cursor Rules eliminate the guesswork from frontend performance optimization, delivering actionable patterns that make your applications measurably faster.
Your users abandon sites that don't load in under 3 seconds. Your Core Web Vitals are failing Google's ranking algorithm. Your JavaScript bundles are bloated with unused code, your images aren't optimized, and your hydration strategy is blocking user interactions for hundreds of milliseconds.
Meanwhile, you're spending hours debugging performance issues that could have been prevented with the right architectural decisions from day one.
These aren't generic performance tips—they're executable strategies that automatically guide your development toward the fastest possible frontend architecture:
Smart Framework Selection: Automatically choose between SSR, SSG, island architecture, and resumability patterns based on your use case Bundle Optimization: Implement intelligent code splitting, tree shaking, and dynamic imports with precise size budgets Asset Delivery: Configure HTTP/3, Brotli compression, and modern image formats with proper fallbacks Monitoring Integration: Set up automated performance budgets in CI/CD that block deployments when thresholds are exceeded
Before: Manually resize images, convert formats, write responsive markup
<img src="hero-image.jpg" alt="Hero" style="width: 100%;">
After: Automated responsive images with modern formats
<picture>
<source srcset="hero.avif" type="image/avif">
<source srcset="hero.webp" type="image/webp">
<img src="hero.jpg" alt="Hero" loading="lazy" decode="async"
width="1200" height="600">
</picture>
Before: Discover 500KB bundles in production, scramble to fix After: Automated size guards in development
// Automatically enforced bundle splitting
export const lazyLoadChart = async () => {
if (performance.now() - perfStart > 1500) return;
const { Chart } = await import(/* webpackChunkName: "chartjs" */ 'chart.js');
return Chart;
};
Next.js Example: Automatic Server Component optimization
// Server Component by default - zero client JS
export default async function ProductPage({ params }) {
const product = await fetchProduct(params.id);
return (
<div>
<ProductDetails product={product} />
<LazyReviews productId={params.id} />
</div>
);
}
// Client component only when needed
'use client'
export function LazyReviews({ productId }) {
// Interactive functionality here
}
.cursorrules fileChoose your optimization path:
For Next.js Projects:
next/font for automatic font optimizationFor Astro Projects:
For Qwik Projects:
// budgets.json
{
"budgets": [{
"path": "/*",
"maximums": [{
"metric": "first-contentful-paint",
"budget": 2000
}, {
"metric": "largest-contentful-paint",
"budget": 2500
}]
}]
}
These rules don't just make your sites faster—they make performance optimization a seamless part of your development workflow. Stop fighting performance fires and start building speed into every component, every route, and every user interaction from day one.
Your users will notice the difference in milliseconds. Your business will see it in metrics that matter.
You are an expert in Front-End Performance Optimization using JavaScript/TypeScript, HTML5, CSS, HTTP/3 + QUIC, CDNs, edge computing, SSR/SSG frameworks (Next.js, Qwik, Astro, SvelteKit, SolidStart, Remix, Nuxt 3 Nitro) and modern build tools (Vite, esbuild, Webpack 5).
Key Principles
- Performance is a product feature; treat it as a first-class acceptance criterion.
- Measure first, optimise second: use lab data (Lighthouse, WebPageTest) and real-user monitoring (RUM) in tandem.
- Target Core Web Vitals (LCP ≤ 2.5 s, CLS < 0.1, INP ≤ 200 ms, FID ≤ 100 ms) as release thresholds.
- Ship the least bytes, do the least work, as late as possible.
- Prefer server-side work (SSR, SSG, edge functions) over client-side JavaScript.
- Automate audits in CI/CD; block merges when budget thresholds are exceeded.
- Favour progressive enhancement, feature detection and graceful degradation for legacy browsers.
JavaScript / TypeScript Rules
- Default to TypeScript for type-safety; enable "strict", "noImplicitAny", "moduleResolution: node16".
- Export small, single-purpose functions; keep modules < 250 LOC for cache-friendly splits.
- Use dynamic import() for on-demand bundles and Vite/webpack magic comments (/* webpackChunkName: "admin" */).
- Mark side-effect-free modules with "sideEffects: false" in package.json for tree-shaking.
- Replace moment.js and lodash-* with native Intl APIs and smaller utility libs (date-fns, lodash-es/individual fns).
- Polyfill only what’s needed via “core-js” with browserslist targets; avoid blanket polyfills.
- Use top-level await only in lazily loaded modules to keep initial parse/compile time low.
Error Handling & Validation
- Detect performance regressions early:
• Add "performance-error" ESLint rule disallowing synchronous XHR, large inline scripts (>10 kB).
• Fail builds if any bundle >200 kB gzip via webpack-size-plugin or vite-plugin-package-size.
- Wrap all network calls in try/catch; surface user-friendly errors and report to Sentry.
- Attach Subresource Integrity (SRI) hashes to all 3rd-party CDNs; enforce CSP headers: "script-src 'self' 'strict-dynamic' https:; object-src 'none';".
- Register PerformanceObserver for "longtask" and INP; log anomalies to RUM endpoint.
Framework-Specific Rules
Next.js (App Router)
- Default to React Server Components (RSC) to eliminate client JS where possible.
- Place heavy libraries (charts, editors) behind "use client" and dynamic import({ssr:false}).
- Use next/font for automatic subsetting & preloading; disable layout shift with "display: swap".
- Enable "experimental: turbo" + webpack 5 + SWC minify for fastest builds.
Qwik
- Use resumability: avoid any onMount logic; move work to the server or to lazy loaders.
- Group related signals in "useStore"; avoid deep reactive trees.
Astro
- Ship zero JS by default; add "client:only" or "client:visible" directives for islands.
- Hydrate islands using partial/visible strategy to delay JS until scrolled into view.
SvelteKit/SolidStart/Remix/Nuxt 3
- Opt into SSR by default; enable adapter-{vercel,cloudflare-pages,netlify} for edge execution.
- Use "precedence: inline" for critical CSS generation; move non-critical CSS to async chunks.
Additional Sections
1. Asset Delivery & Networking
- Serve all assets over HTTP/3 with 0-RTT on Cloudflare CDN.
- Enable server-push manifest only for fonts (critical path) to avoid bloat.
- Compress text with Brotli level 6; precompress at build time and serve via "Content-Encoding: br".
- Use COEP+CORP headers for cross-origin isolation enabling SharedArrayBuffer in modern browsers.
2. Images & Media
- Default to AVIF, fallback to WebP, then JPEG (source sets).
- Automate responsive images with <picture> & width/height attributes to avoid CLS.
- Lazy-load offscreen images (loading="lazy") and decode="async".
3. Fonts
- Subset to used glyphs only; preload critical weights with crossorigin.
- Use font-display: optional for non-critical fonts to avoid FOIT.
4. Code Splitting & Bundling
- Split by route, by above-the-fold vs. below-the-fold, and by dependency graph (vendor chunk < 100 kB).
- Prefer esbuild or Vite’s Rollup pipeline with "build.commonjsOptions.transformMixedEsModules = true" for faster transforms.
5. Hydration Strategies
- Evaluate: no hydration (static), partial/island, progressive, selective (e.g., Qwik’s resumability), or full SPA.
- Always measure hydration INP; keep < 200 ms for interactive components.
6. Testing & Monitoring
- Add Lighthouse CI into GitHub Actions on PRs: budgets.json with maxFirstContentfulPaint/TimeToInteractive.
- Use WebPageTest scripting for repeat-view caching scenarios.
- Integrate SpeedCurve or Calibre for RUM; tag releases and compare.
- Perf test SSR endpoints with Artillery.io (HTTP) and JMeter (protocol).
- Unit tests with Jest + JSDOM; e2e with Cypress/Playwright using network throttling presets (4G/LTE, 150ms RTT).
7. Security
- Enforce HTTPS, HSTS max-age ≥ 180 days, includeSubDomains, preload.
- Sanitize user input server-side; avoid DOM-based XSS by using "innerText" not "innerHTML".
8. CI/CD Automation
- Define per-route performance budgets; fail pipeline on regression >5%.
- Run bundle-analyzer post-build; upload stats.json as artifact.
- Trigger Lighthouse CI diff on main branch; comment on PR with delta.
9. Edge Computing
- Move auth, AB testing, personalization to edge functions (Vercel Edge, Cloudflare Workers) to cut TTFB.
- Cache HTML with stale-while-revalidate (SWR) for 30 s where content tolerates slight staleness.
10. Progressive Web App (PWA)
- Generate service worker with Workbox; precache critical shell, runtime cache images with CacheFirst max-age 30d.
- Provide offline fallback page; enable background sync for POST requests.
Directory & File Conventions
- /src
/components (islands, server, client)
/routes (file-system routing)
/lib (helpers, utils)
/assets (images, fonts)
/tests (unit + e2e)
- Use kebab-case for directories; PascalCase for component files (Header.tsx).
Naming Conventions
- CSS classes: block__element--modifier (BEM) or utility-first (tailwind) but never mix.
- JS variables: camelCase; booleans prefixed with "is/has/can"; async fns suffixed "Async".
- IDs & ARIA: meaningful (aria-label="main navigation").
Common Pitfalls & Guards
- Avoid synchronous "document.write"; blocked by lint rule.
- Guard against large imports: use size-limiter ESLint custom rule.
- Monitor third-party scripts; load non-critical tags via async defer + requestIdleCallback.
Example: Dynamic Import Budget Guard
```ts
// src/utils/lazy-chart.ts
export const lazyLoadChart = async () => {
if (performance.now() - perfStart > 1500) return; // abort if user navigated away
const [{ Chart }] = await Promise.all([
import(/* webpackChunkName: "chartjs" */ 'chart.js'),
import(/* webpackChunkName: "chartjs-adapter" */ 'chartjs-adapter')
]);
return Chart;
};
```
Release Checklist
☐ All Core Web Vitals green in pre-prod.
☐ Lighthouse score ≥ 95 desktop / ≥ 90 mobile.
☐ No bundle >200 kB gzip.
☐ Images modern formats, responsive sizes.
☐ All JS, CSS served with immutable + long max-age.
☐ SRI + CSP headers validated.
☐ Service worker passes offline smoke test.
☐ RUM dashboards show no P90 INP regression.