AI Rules for SEO Optimization in Code
AI generates client-rendered pages with no meta tags. Rules for server-side rendering, dynamic metadata, structured data (JSON-LD), sitemaps, and Core Web Vitals optimization.
Proven patterns for writing effective AI coding rules and maintaining standards across repos.
AI generates client-rendered pages with no meta tags. Rules for server-side rendering, dynamic metadata, structured data (JSON-LD), sitemaps, and Core Web Vitals optimization.
AI hardcodes English strings in components and templates. Rules for message catalogs, ICU message format, date/number Intl formatting, pluralization, and RTL layout support.
AI uses Math.random() for A/B tests — users flip between variants. Rules for deterministic hashing, sample size, statistical significance, experiment platforms, and variant tracking.
When AI follows your rules, code reviews shift from 'change this pattern' to 'is this the right approach?' Learn how rules upgrade your review process.
AI hardcodes feature toggles as if-statements scattered through the codebase. Rules for flag services, typed flags, gradual rollout, kill switches, and stale flag cleanup.
AI generates migrations that lock tables for minutes and drop data. Rules for zero-downtime patterns, two-phase column changes, data backfills, rollback, and migration testing.
AI writes tests that are either trivially shallow or painfully over-mocked. Rules for meaningful tests: what to test, what to mock, and how to structure test files.
AI-generated APIs often have inconsistent response formats, missing validation, and poor error handling. These rules fix the patterns that matter most.
AI processes everything in the request handler — blocking users for seconds. Rules for job queues (BullMQ, Celery), retry with backoff, dead letter queues, idempotent jobs, and worker scaling.
AI generates regex that's either vulnerable to ReDoS or fails on edge cases. Rules for safe patterns, named groups, readability, and using parser libraries instead.
AI assistants generate working code that's subtly insecure. Learn the top 5 vulnerability patterns and the specific rules that prevent each one at generation time.
AI-generated proto files break backward compatibility and use wrong field types. Rules for schema evolution, field numbering, service design, and gRPC error handling.
AI processes webhooks synchronously with no signature check. Rules for HMAC signature verification, idempotent processing, async queuing, retry handling, and event logging.
AI sends email in the request handler — blocking the response for 2 seconds. Rules for background queues, Resend/SendGrid, React Email templates, and deliverability basics.
AI builds visual-only UIs invisible to screen readers. Rules for landmark regions (nav, main, aside), heading hierarchy (h1-h6 no skips), accessible names for all controls, logical reading order, dynamic content announcements, and testing with NVDA and VoiceOver.
AI builds mouse-only interfaces. Rules for logical tab order, focus management in modals and SPAs, roving tabindex for composite widgets, skip-to-content links, keyboard shortcut design, and :focus-visible styling that does not annoy mouse users.
AI misuses or ignores ARIA. Rules for the five rules of ARIA usage, correct role assignments, aria-expanded and aria-selected state attributes, aria-live regions for dynamic updates, and the most common ARIA anti-patterns to avoid.
AI fails WCAG on every criterion. Rules for perceivable content (alt text, contrast, captions), operable controls (keyboard, timing, seizures), understandable interfaces (labels, errors, predictability), robust markup (valid HTML, ARIA), and axe-core accessibility testing in CI.
AI builds JS-dependent apps that show blank pages. Rules for HTML-first server rendering, form actions that work without JavaScript, CSS-only interactive patterns, feature detection with fallbacks, and graceful degradation that preserves core functionality.
AI treats offline as an error. Rules for local-first data architecture, IndexedDB as primary store, sync engines for background reconciliation, conflict resolution strategies, optimistic UI patterns, and connectivity-aware UX indicators.
AI registers service workers with no caching strategy. Rules for cache-first and network-first strategies, Workbox precaching, runtime route caching, service worker update prompts, PWA installability criteria, and offline fallback pages.
AI blocks the main thread with heavy computation. Rules for Web Worker offloading, structured clone data transfer, Comlink for RPC-style messaging, SharedWorker for cross-tab state, worker pool patterns, and Transferable objects for zero-copy.
AI uses WebSocket for one-way push. Rules for native EventSource API, SSE vs WebSocket selection criteria, streaming response patterns, built-in automatic reconnection, typed event channels, Last-Event-ID resume, and serverless-compatible SSE.
AI polls GraphQL queries every second. Rules for WebSocket-based subscriptions, subscription resolvers with async iterators, Redis pub/sub backend, event filtering per subscriber, connection lifecycle management, and horizontal scaling strategies.
AI couples services with direct calls. Rules for topic-based event broadcasting, fan-out to multiple subscribers, message attribute filtering, at-least-once delivery semantics, subscription lifecycle management, and when to use pub/sub vs point-to-point queues.
AI processes everything inline. Rules for queue selection (SQS, BullMQ, RabbitMQ), producer/consumer decoupling, dead letter queues, FIFO ordering guarantees, at-least-once with idempotent consumers, and backpressure with concurrency limits.
AI wraps cross-service calls in one transaction. Rules for saga choreography and orchestration, compensating actions for rollback, transactional outbox pattern, two-phase commit trade-offs, and eventual consistency with conflict resolution.
AI creates duplicates on retries and double-charges on timeouts. Rules for Idempotency-Key headers, Redis/database deduplication stores, naturally idempotent operations, conditional updates with ETags, and idempotency key TTL lifecycle.
AI retries immediately and infinitely. Rules for exponential backoff with jitter, max retry limits, idempotent-only retries, error classification (retryable vs permanent), retry budgets, and AbortController timeout integration.
AI retries infinitely with no backoff. Rules for circuit breaker state machines (closed/open/half-open), failure thresholds, graceful fallback responses, health probe half-open testing, bulkhead isolation, and opossum library patterns.
AI has no mTLS or traffic management between services. Rules for sidecar proxy architecture, mutual TLS for zero-trust, traffic splitting for canary deployments, integrated observability, retry/timeout policies, and when a service mesh is worth the complexity.
AI exposes microservices directly to clients. Rules for API gateway request routing, edge rate limiting, authentication offloading, response aggregation from multiple services, request/response transformation, and gateway selection criteria.
AI builds custom SSO instead of supporting standards. Rules for SAML 2.0 service provider integration, OIDC support, just-in-time user provisioning, federated session management, domain-based SSO enforcement, and enterprise IdP requirements.
AI sends SMS codes with no rate limits or recovery. Rules for TOTP with authenticator apps, WebAuthn passkeys, hashed recovery codes, enrollment UX with QR codes, graceful enforcement policies, and backup method management.
AI stores provider tokens in localStorage with no linking. Rules for NextAuth provider configuration, safe account linking with verification, profile data sync, token refresh for API access, multi-provider management, and login button UX.
AI requests push on page load and blasts everyone. Rules for progressive push permission UX, service worker registration, rich notification payloads with actions, audience segmentation, frequency capping, and opt-out management.
AI loads the full Maps SDK on every page. Rules for lazy loading map libraries, marker clustering for large datasets, custom map styles, static image fallbacks for non-interactive contexts, and map API cost optimization.
AI requests location on page load with no context. Rules for progressive permission UX, IP geolocation fallback, PostGIS spatial queries for nearby search, privacy-preserving fuzzy location, reverse geocoding, and timezone detection.
AI uses last-write-wins for concurrent edits. Rules for CRDTs and operational transforms, presence awareness with cursors, conflict-free merging, optimistic local-first updates, undo/redo in collaborative contexts, and awareness indicators.
AI polls every second for new messages. Rules for WebSocket real-time delivery, message ordering with sequence numbers, read receipts, typing indicators, offline queuing with sync, and conversation threading models.
AI serves video as a full file download. Rules for HLS adaptive bitrate streaming, CDN edge delivery, FFmpeg transcoding pipelines, thumbnail sprite generation, HTTP range request support, and video player integration.
AI processes images inline with no size limits. Rules for sharp-based resize/convert pipelines, async background processing, WebP/AVIF output, thumbnail generation at multiple sizes, EXIF metadata stripping, and upload validation.
AI splits on commas and breaks on quoted fields. Rules for Papa Parse/csv-parse streaming, encoding detection, header mapping with column aliases, per-row Zod validation, edge case handling, and memory-efficient large file processing.
AI concatenates HTML strings for PDFs with no page breaks. Rules for Puppeteer/Playwright headless rendering, React-to-PDF pipelines, Handlebars templates, CSS page break control, header/footer injection, and async generation.
AI exports synchronously and times out. Rules for async background export jobs, streaming CSV/JSON generation, chunked import with row-level validation, progress tracking with webhooks, and GDPR data portability compliance.
AI uses console.log or logs nothing. Rules for structured audit events with who/what/when/why, immutable append-only trails, compliance-ready retention policies, tamper-evident logging, and queryable audit search.
AI builds single-tenant apps. Rules for tenant isolation with row-level security, schema-per-tenant vs shared-database trade-offs, tenant-aware middleware, data isolation guarantees, and cross-tenant query prevention.
AI builds subscriptions with no proration or dunning. Rules for plan management with Stripe Billing, trial-to-paid conversion, proration on plan changes, dunning for failed renewals, usage-based metered billing, and revenue recognition.
AI builds leaky multi-page checkout. Rules for single-page checkout design, cart persistence across sessions, address validation and autocomplete, live order summary, graceful error recovery, and conversion rate optimization.
AI processes raw card numbers server-side with no webhook verification. Rules for Stripe Checkout sessions, webhook signature verification, idempotent charges, refund workflows, subscription lifecycle, and PCI DSS compliance.
AI sends notifications inline with no preferences or batching. Rules for multi-channel delivery (email, push, in-app), user preference management, intelligent batching, template systems, and delivery tracking with retry.
AI searches with LIKE '%query%'. Rules for Postgres full-text search, Elasticsearch integration, BM25 relevance scoring, fuzzy matching with typo tolerance, faceted filtering, and debounced search-as-you-type.
AI maps classes to tables 1:1 with no relationship analysis. Rules for entity-relationship modeling, cardinality constraints, polymorphic data patterns, soft delete strategies, temporal data versioning, and schema evolution.
AI uses NoSQL like a relational DB. Rules for access-pattern-driven data modeling, single-table design in DynamoDB, strategic denormalization, consistency model selection, and clear criteria for choosing NoSQL vs SQL.
AI stores uploads on the local filesystem and trusts filenames. Rules for S3/R2 object storage, MIME validation, signed URLs for private files, size limits, and virus scanning.
AI builds tables with no indexes or constraints. Rules for normalization to 3NF, strategic index design, foreign key constraints, migration-first workflows, query performance analysis, and schema evolution strategies.
AI rewrites everything at once. Rules for strangler fig incremental migration, module extraction sequencing, data migration with dual-write periods, API gateway routing, feature flag cutover, and rollback safety.
AI-generated CSS is riddled with specificity issues, magic numbers, and non-responsive layouts. Rules for your styling approach — Tailwind, CSS Modules, or vanilla CSS.
AI builds distributed monoliths. Rules for service boundary design, API contract testing, circuit breaker resilience, service mesh observability, distributed tracing, and when microservices are premature.
AI wires logic directly to infrastructure. Rules for ports and adapters pattern, driving vs driven ports, primary and secondary adapters, hexagonal testability, and swappable infrastructure without domain changes.
AI tangles business logic with frameworks and databases. Rules for dependency inversion, use case interactors, interface adapters, framework-independent domain, and testability through layer boundaries.
AI builds anemic models with scattered logic. Rules for ubiquitous language, bounded contexts, aggregate boundaries, value objects, domain events, repository pattern, and anti-corruption layers between contexts.
AI uses one model for reads and writes. Rules for command/query separation, event store append-only logs, read model projections, snapshot optimization, temporal queries, and when CQRS is overkill.
AI chains synchronous calls for async workflows. Rules for event schemas, message queues (SQS, BullMQ), saga orchestration, dead letter queues for failures, idempotent consumers, and eventual consistency.
AI treats serverless like traditional servers. Rules for stateless function design, cold start mitigation, connection pooling strategies, idempotent operations, timeout handling, and cost-aware architecture.
AI writes verbose, unstructured documentation. Rules for README templates, API doc conventions, heading structure, code examples, and technical writing style.
AI deploys to one region ignoring edge runtimes. Rules for edge-compatible code patterns, middleware at the edge, data locality strategies, edge caching with stale-while-revalidate, and edge runtime constraints.
AI blocks rendering until all data resolves. Rules for streaming HTML with React Suspense, progressive shell-first rendering, out-of-order streaming, TTFB optimization, and fallback loading strategies.
AI marks every file 'use client' and fetches in useEffect. Rules for server-first component architecture, minimal client boundaries, server actions for mutations, Suspense streaming, and zero-waterfall data fetching.
AI builds monolithic frontends or splits at wrong boundaries. Rules for vertical domain slices, Module Federation, shared dependency management, event-bus communication, and independent deployment pipelines.
AI builds one-off components with hardcoded colors. Rules for design token systems, variant-based component APIs, accessible primitive components, Storybook-driven development, and consistent API patterns.
AI builds 500-line god components. Rules for single responsibility, container/presentational split, composition over configuration, context for prop drilling, custom hooks for logic extraction, and file colocation.
AI animates with JavaScript and ignores motion preferences. Rules for CSS transitions over JS animation, GPU-accelerated transform/opacity, Framer Motion, prefers-reduced-motion, and 60fps animation performance.
AI inverts colors for dark mode. Rules for CSS custom properties theming, prefers-color-scheme detection, localStorage persistence, WCAG contrast ratios in both themes, and semantic color token systems.
AI builds fixed-width desktop layouts. Rules for mobile-first CSS, fluid typography with clamp(), container queries, responsive image srcset, touch-friendly target sizes, and viewport meta configuration.
AI ignores Core Web Vitals entirely. Rules for measuring LCP, INP, and CLS, optimizing each metric, RUM monitoring with web-vitals library, and CI performance budgets that catch regressions.
AI serves uncompressed PNGs at 4000px. Rules for WebP/AVIF format selection, responsive srcset with sizes, Next.js Image component, CDN image delivery, and automated compression in build pipelines.
AI loads everything upfront. Rules for native image lazy loading, Intersection Observer for components, progressive data fetching, skeleton loading states, and fetchpriority hints for critical content.
AI ships one massive JavaScript bundle. Rules for route-based code splitting, dynamic imports, React.lazy with Suspense boundaries, vendor chunk optimization, and CI bundle size monitoring.
AI installs packages blindly. Rules for dependency audits, bundle size impact analysis, lockfile management, semantic versioning update strategies, and supply chain security with integrity checks.
AI hardcodes API keys and never rotates them. Rules for HashiCorp Vault and AWS Secrets Manager, automated rotation schedules, zero-downtime rollover, CI secret scanning, and leak incident response.
AI stores API keys and PII as plain text in the database. Rules for AES-256-GCM field-level encryption, KMS key management, envelope encryption, key rotation, and data classification policies.
AI uses HTTP URLs and skips HSTS. Rules for TLS 1.3, HSTS preloading, automated certificate management with Let's Encrypt, HTTP-to-HTTPS redirects, and modern cipher suite configuration.
AI ships zero CSP headers — any injected script runs freely. Rules for script-src with nonces, style-src, connect-src allowlists, frame-ancestors, CSP report-uri, and incremental rollout via report-only mode.
AI sets CORS to allow-all origins. Rules for origin allowlists, credentials with specific origins, preflight cache optimization, exposed headers, and per-environment CORS configuration.
AI interpolates user input into queries and templates with no sanitization. Rules for parameterized queries, context-aware output encoding, allowlist validation, and injection prevention across SQL, HTML, and OS commands.
AI returns raw database rows as API responses. Rules for DTO patterns, response shaping, ISO 8601 dates, consistent naming conventions, pagination envelopes, and never exposing internal IDs or fields.
AI returns generic 500 errors for everything. Rules for structured error responses with machine-readable codes, user-facing messages, field-level validation errors, and docs links in error payloads.
AI builds APIs with no documentation. Rules for OpenAPI/Swagger specs, request/response examples, error code catalogs, authentication docs, and auto-generated SDK documentation.
AI builds APIs with no versioning — breaking changes break every client. Rules for URL path versioning, Accept header versioning, deprecation timelines, additive changes, and migration guides.
AI creates sessions with no expiration and client-only logout. Rules for Redis-backed sessions, idle and absolute timeouts, session regeneration on privilege change, and concurrent session limits.
AI exposes client secrets in frontend code and skips CSRF protection. Rules for Authorization Code + PKCE, state parameter validation, secure token exchange, scopes, and account linking.
AI creates JWTs with no expiration stored in localStorage. Rules for RS256 signing, minimal claims, httpOnly cookie storage, refresh token rotation, token families, and revocation strategies.
AI scatters role checks across every route handler. Rules for RBAC with permission hierarchies, ABAC policies, middleware-enforced authorization, and principle of least privilege.
AI stores passwords in plain text and skips session invalidation. Rules for bcrypt hashing, JWT refresh rotation, MFA integration, OAuth flows, and secure session lifecycle.
AI validates with if-statements and shows errors one at a time. Rules for Zod/Yup schema validation, React Hook Form, field-level errors, accessible error display, and server-side validation.
AI fetches all records then slices in JS. Rules for database-level pagination: cursor-based for APIs, offset with limits, keyset for performance, and infinite scroll implementation.
AI-generated GraphQL has N+1 resolvers, no pagination, and missing input validation. Rules for schema design, DataLoader batching, and query complexity limiting.
AI caches nothing or caches everything with no invalidation. Rules for cache-aside pattern, TTL configuration, invalidation strategies, cache stampede prevention, and multi-layer caching.
AI puts API data, form state, and UI toggles in one Redux store. Rules for server/client state separation, state colocation, derived state over redundant state, and choosing the right tool.
AI generates SQL with string interpolation, missing indexes, and N+1 patterns. Rules for parameterized queries, proper joins, indexing strategy, and migration safety.
AI generates APIs with zero rate limiting — open to abuse and DDoS. Rules for token bucket algorithms, sliding window, per-user limits, 429 responses, and Redis-backed limiters.
AI awaits in sequence or Promise.all with 10,000 items. Rules for controlled concurrency: Promise.all for small batches, p-limit for bounded parallelism, and race condition prevention.
AI-generated HTML uses divs for everything and ignores accessibility. Rules for semantic elements, ARIA, keyboard navigation, and WCAG 2.1 AA compliance.
AI puts secrets in config files and hardcodes environment-specific values. Rules for environment separation, schema validation, secrets management, and config structure.
AI uses console.log for everything — unstructured, unsearchable, no context. Rules for structured JSON logging, log levels, correlation IDs, and the three pillars of observability.
Most AI rule files are too vague to be useful. These 7 best practices — with before/after examples — will dramatically improve the code your AI assistant generates.
AI creates memory leaks in every language. Rules for cleanup on unmount, WeakRef for caches, event listener removal, growing collection limits, and heap profiling with DevTools.
AI-generated Bash is fragile by default: unquoted variables, missing error handling, and unsafe patterns. Rules for shellcheck compliance, quoting, and safe scripting.
AI catches Exception, swallows errors, and logs with console.error. Rules for typed error hierarchies, narrow catch scopes, error boundaries, retry patterns, and structured logging.
AI either ignores performance or optimizes prematurely. Rules for measurement-first optimization, performance budgets, lazy loading, code splitting, and profiling before fixing.