Skip to content

Add React/Next.js, TypeScript, Python, Go production rules#300

Open
oliviacraft wants to merge 4 commits into
PatrickJS:mainfrom
oliviacraft:add-mdc-production-rules
Open

Add React/Next.js, TypeScript, Python, Go production rules#300
oliviacraft wants to merge 4 commits into
PatrickJS:mainfrom
oliviacraft:add-mdc-production-rules

Conversation

@oliviacraft
Copy link
Copy Markdown
Contributor

@oliviacraft oliviacraft commented May 31, 2026

Production-tested rules for 4 common stacks

Adding .cursorrules files for 4 stacks based on the most common AI code generation failure modes:

  • React + Next.js App Router — Server vs Client boundary, data fetching, error states
  • TypeScript strict mode — no-any enforcement, discriminated unions, typed env vars
  • Python production — type hints, error handling, Pydantic, dependency injection
  • Go production — error wrapping, interface placement, context propagation, goroutine ownership

Each rule targets the specific pattern AI generates incorrectly for that stack — not generic best practices.

These files follow the existing .cursorrules format in this repo. There's also an .mdc version available for Cursor agent mode (which uses a different format): cursor-mdc-rules

Summary by CodeRabbit

  • Documentation
    • Added Go production coding guidelines covering error handling, context usage, interface and goroutine patterns, and test structure.
    • Added Python/FastAPI standards requiring explicit typing, Pydantic models at API boundaries, async-safe patterns, and startup validation.
    • Added React/Next.js guidance for Server/Client component conventions, data-fetching, routing, and component organization.
    • Added TypeScript strict-mode standards to enforce strict typing, immutability patterns, and safer startup validation.

@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai Bot commented May 31, 2026

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 258a913d-54ce-4ee1-bad4-3160c0df51b8

📥 Commits

Reviewing files that changed from the base of the PR and between bb84ab3 and ae4cd00.

📒 Files selected for processing (1)
  • rules/go-production/.cursorrules
✅ Files skipped from review due to trivial changes (1)
  • rules/go-production/.cursorrules

📝 Walkthrough

Walkthrough

Four .cursorrules configuration files are added or updated to define production coding best practices for Go, Python/FastAPI, TypeScript strict mode, and React/Next.js App Router.

Changes

Production Coding Rules for Multiple Tech Stacks

Layer / File(s) Summary
Go Production Rules
rules/go-production/.cursorrules
Error handling with contextual wrapping, interface placement in consumer packages, context.Context as first parameter for I/O, goroutine lifecycle management via errgroup, named struct fields, and table-driven tests with t.Run.
Python/FastAPI Production Rules
rules/python-fastapi-production/.cursorrules
Type-hinted function signatures, forbidden bare except, Pydantic BaseModel for API boundaries, dependency injection via parameters, pathlib.Path path handling, asyncio.sleep() in async code, and startup environment variable validation.
TypeScript Strict Production Rules
rules/typescript-strict-production/.cursorrules
tsconfig.json strict mode enforcement, prohibition of any types, explicit return types for exported functions, discriminated-union state patterns, immutability via Readonly<T> and as const, startup environment validation, and TypeScript enum ban in favor of const objects.
React/Next.js Production Rules
rules/react-nextjs-production/.cursorrules
Server Components as default, use client boundary specification, server actions for mutations, one component per file with PascalCase, explicit Props interfaces, required loading.tsx/error.tsx for async routes, and Next.js library usage (next/image, next/font).

Estimated code review effort

🎯 1 (Trivial) | ⏱️ ~3 minutes

Suggested reviewers

  • PatrickJS

Poem

🐰 Rules sown neat across four rows of code,
Go, Python, TS, and React all sowed,
Guides to follow, tidy and bright,
Cursor rules to steer the night,
A rabbit cheers: ship safe, ship light!

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 inconclusive)

Check name Status Explanation Resolution
Description check ❓ Inconclusive The description covers the Summary and Contribution Type sections clearly, explaining the practical value and which files were added. However, the Quality Checklist items are unchecked, indicating the author did not complete the required template sections. Complete the Quality Checklist section by checking applicable items and verify that all files meet the specified quality standards (descriptive naming, proper formatting, no duplicates, etc.).
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title accurately and concisely summarizes the main change: adding production rules for four technology stacks (React/Next.js, TypeScript, Python, Go).
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

Copy link
Copy Markdown
Contributor

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🧹 Nitpick comments (2)
rules/python-fastapi-production/.cursorrules (2)

1-1: ⚡ Quick win

Update title to match directory name and scope.

The title says "Python Production" but the directory is python-fastapi-production and the rules specifically reference FastAPI-related patterns (e.g., Pydantic BaseModel at API boundaries). Consider updating to "Python/FastAPI Production" for consistency.

📝 Suggested title update
-.cursorrules — Python Production
+.cursorrules — Python/FastAPI Production
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@rules/python-fastapi-production/.cursorrules` at line 1, Update the rules
title string "Python Production" to reflect the directory and scope by changing
it to "Python/FastAPI Production" (or similar) so it explicitly references
FastAPI; locate the title declaration in the .cursorrules content where "Python
Production" appears and replace it with "Python/FastAPI Production", and ensure
any header or metadata that repeats the title is updated consistently.

9-9: ⚡ Quick win

Clarify what "silent defaults" means.

The phrase "No os.environ.get() silent defaults" could be interpreted multiple ways. Consider being more explicit about the problematic pattern.

📝 Suggested clarification
-Validate env vars at startup. No os.environ.get() silent defaults.
+Validate required env vars at startup. No os.environ.get(key, default) fallbacks that hide missing config.

Or alternatively:

-Validate env vars at startup. No os.environ.get() silent defaults.
+Explicitly validate env vars at startup. Fail fast on missing required config—avoid os.environ.get() with fallback defaults.
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@rules/python-fastapi-production/.cursorrules` at line 9, Replace the
ambiguous phrase "No os.environ.get() silent defaults" with an explicit
description and examples: state that patterns like os.environ.get('FOO',
'default') or os.getenv('FOO', 'default') which silently fall back to a default
are disallowed, and recommend the allowed alternatives (e.g., use
os.environ['FOO'] to fail fast or a centralized validator at startup that raises
a clear error). Update the rule text so it contains both the problematic code
snippets and the preferred patterns (and mention the rule's intent to validate
env vars at startup).
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@rules/react-nextjs-production/.cursorrules`:
- Around line 1-9: Update the .cursorrules text to soften absolutes: change the
sentence about "Every async route needs a sibling loading.tsx and error.tsx" to
state that loading.tsx and error.tsx are recommended route-segment UI/boundaries
and that missing files fall back to Next.js defaults; likewise modify the rules
referencing "Server Actions for mutations, not client-side API route calls" and
"Never fetch in useEffect" to use wording like "prefer Server Actions for
mutations when appropriate" and "prefer fetching in Server Components; avoid
useEffect for data fetching when possible," so the file mentions
recommendation/preference rather than strict prohibition for
"loading.tsx"/"error.tsx", "Server Actions", and "useEffect".

---

Nitpick comments:
In `@rules/python-fastapi-production/.cursorrules`:
- Line 1: Update the rules title string "Python Production" to reflect the
directory and scope by changing it to "Python/FastAPI Production" (or similar)
so it explicitly references FastAPI; locate the title declaration in the
.cursorrules content where "Python Production" appears and replace it with
"Python/FastAPI Production", and ensure any header or metadata that repeats the
title is updated consistently.
- Line 9: Replace the ambiguous phrase "No os.environ.get() silent defaults"
with an explicit description and examples: state that patterns like
os.environ.get('FOO', 'default') or os.getenv('FOO', 'default') which silently
fall back to a default are disallowed, and recommend the allowed alternatives
(e.g., use os.environ['FOO'] to fail fast or a centralized validator at startup
that raises a clear error). Update the rule text so it contains both the
problematic code snippets and the preferred patterns (and mention the rule's
intent to validate env vars at startup).
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: a7b0f8cb-0f9d-4ee8-8a95-9ee23719e912

📥 Commits

Reviewing files that changed from the base of the PR and between b044f95 and bb84ab3.

📒 Files selected for processing (4)
  • rules/go-production/.cursorrules
  • rules/python-fastapi-production/.cursorrules
  • rules/react-nextjs-production/.cursorrules
  • rules/typescript-strict-production/.cursorrules

Comment on lines +1 to +9
.cursorrules — React + Next.js App Router

- Default to Server Components. Add "use client" only for hooks/browser APIs/event handlers.
- Fetch data in Server Components. Never fetch in useEffect.
- Use server actions for mutations, not client-side API route calls.
- One component per file. File name = component name (PascalCase).
- Define explicit interface Props. Never use any as prop type.
- Every async route needs a sibling loading.tsx and error.tsx.
- Use next/image instead of img. Use next/font instead of Google Fonts link tags.
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

🧩 Analysis chain

🌐 Web query:

Next.js App Router best practices 2026 Server Components server actions loading error

💡 Result:

Best practices for Next.js App Router (2026) around Server Components, Server Actions, streaming/loading, and handling the common “loading / Server Actions error” issues (incl. “Failed to find Server Action”): 1) Default to Server Components; isolate interactivity in Client Components - In the App Router, Server Components are the default; add “use client” only when you need browser-only behavior (state/effects/event handlers/browser APIs) (DEV explanation, aligned with Next.js RSC model) [1]. 2) Use Server Components for data fetching; use Server Actions for mutations - Next.js Server Functions (Server Actions) are designed for server-side mutations; for reading data, use Server Components (and/or Route Handlers) (official docs) [2][3]. 3) Handle “expected” errors in Server Actions with return values + useActionState - Next.js distinguishes expected errors vs unexpected exceptions, and for Server Functions recommends modeling expected errors as return values (not try/catch) and surfacing them via the useActionState hook (official docs) [4]. - Practical pattern: in a Client Component, call useActionState(action, initialState) and render UI based on state (official example pattern) [4]. 4) Use error.tsx / not-found.tsx boundaries for Server Component render errors - For route segment error boundaries in App Router, use error.tsx (and not-found.tsx for 404-like missing resources) (Next.js Learn) [5]. - error boundaries catch errors during rendering; they’re not a catch-all for all runtime failures [4]. 5) Loading UX in App Router: prefer loading.tsx/loading.js + Suspense boundaries - Next.js supports route-segment loading UI via the special loading.js file colocated next to page.js; it wraps that segment in a Suspense boundary and shows the fallback instantly while page content streams [6][7]. - Important caveat: if the layout accesses uncached/runtime data (e.g., cookies, headers, or uncached fetches), loading.js may not show a fallback for it; to preserve streaming, move that work into page.js or wrap runtime access in your own Suspense boundary [6][7]. 6) Server Action loading/pending states: use useActionState (and pending) for submit buttons - While a Server Function is executing, you can show a loading indicator using useActionState, which returns a pending boolean (official docs) [2][8]. 7) Common “Server Actions error” causes and fixes A) “Failed to find Server Action … This request might be from an older or newer deployment” (very common in production) - This error can happen when the server can’t match the incoming request to a known Server Action in the currently running build (discussion/issue examples show the exact message) [9][10]. - Operational best practice: ensure you deploy the same build artifact consistently and avoid serving mismatched builds between instances (the error message itself indicates a deployment/build mismatch) [9]. - If you’re self-hosting/multi-instance, also ensure NEXT_SERVER_ACTIONS_ENCRYPTION_KEY is set at build time (so action IDs/encryption are consistent across builds/instances) [9]. B) Server Action wiring mistakes that produce “Invalid action” / wrong action prop - Make sure the function used as a form action is actually a Server Action (marked with “use server” and is async) and is imported from the correct server module scope; otherwise the action prop is invalid and you’ll see errors like “Invalid value for prop action …” (summary of typical causes) [11]. C) “Server Actions seem to break after upgrading Next.js” - There are documented regressions where Server Actions fail (e.g., “Failed to find Server Action” after upgrading from 14.2.7 to 14.2.8) (GitHub issues) [12][10]. - If you hit this, verify you’re on a fixed version and reproduce with minimal action imports; also check action/module boundaries and ensure the server action is not accidentally converted to something else by imports/usage patterns (examples indicate the error is tied to runtime build/action mapping) [10]. 8) A concise “2026 mental model” checklist - Reads: Server Components (streaming where possible) [2][3]. - Writes: Server Actions (use “use server”, return structured expected errors, revalidate/refresh appropriately) [2][3]. - Errors: useActionState for expected Server Function errors [4]; use error.tsx/not-found.tsx for render-time boundaries [5][4]. - Loading: loading.tsx/loading.js for route segments; avoid uncached/runtime data in layout unless wrapped correctly [6][7]. - Production reliability: watch for “Failed to find Server Action” deployment/build mismatches; ensure consistent build artifacts + required encryption key configuration if applicable [9]. If you paste your specific stack trace (especially the exact message and the files involved: action module, form component, and route segment level of loading/error boundaries), I can map it to the likely bucket above and suggest the minimal fix.

Citations:


🌐 Web query:

Next.js next/image next/font recommended usage 2026

💡 Result:

Recommended usage (Next.js in 2026): 1) next/image - Always size the image to avoid layout shift (CLS). The docs state width/height are used to infer aspect ratio and avoid layout shift, and they do not determine rendered size (CSS does). [1][2] - If you know the height/width, use width/height. - If height/width are unknown, use fill. When using fill, the parent must have position: relative (or fixed/absolute depending on context), and fill expands to the parent. [1][3] - For remote images, Next.js cannot inspect remote files at build time, so you must provide width and height manually (or use fill). [2] - If the image is responsive (especially with fill), provide a realistic sizes prop; without sizes the browser may download unnecessarily large images. [3] - For above-the-fold / LCP images, newer guidance de-emphasizes priority and instead points to using loading="eager" or fetchPriority="high". [4] Example patterns (officially consistent with the docs) - Known aspect ratio (width/height): ... [1] - Unknown aspect ratio (fill): <div style={{ position: 'relative', width: '400px', height: '300px' }}> <Image src="/photo.jpg" alt="Photo" fill style={{ objectFit: 'cover' }} /> [3] - Remote image (manually provide dimensions): ... [2] 2) next/font - Use next/font (next/font/google or next/font/local) to get automatic font optimization and self-hosting, eliminating external network requests and helping prevent layout shift. [5][6] - Apply fonts via the className returned by the loader, and to make a font global in the App Router, add it in the Root Layout (analogously _app for Pages Router). [5][6] - Prefer variable fonts when possible; otherwise specify required weights. [5] 3) Putting them together (practical 2026 checklist) - Fonts: import via next/font and apply the returned className at the appropriate layout/root. [5][6] - Images: every next/image instance should be either (a) width/height (so Next can reserve aspect-ratio space) or (b) fill with a sized parent; for fill/responsive layouts, set sizes. [1][3] - Remote images: always provide width/height (or use fill) since Next can’t read remote dimensions at build time. [2] - For the LCP/hero image: use loading="eager" or fetchPriority="high" (the docs/implementation guidance updates away from relying on the older priority prop). [4]

Citations:


Soften/adjust App Router rules for loading/error and mutation guidance

  • loading.tsx / error.tsx are recommended route-segment UI/boundaries, but they’re not required for every async route segment (missing files fall back to Next.js defaults), so revise the “Every async route needs…” wording (line 8).
  • The “Server Actions for mutations, not client-side API route calls” and “Never fetch in useEffect” rules are too absolute for current docs; adjust to “prefer” / “use when appropriate” (lines 4-5) to avoid steering codegen into unnecessary patterns.
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@rules/react-nextjs-production/.cursorrules` around lines 1 - 9, Update the
.cursorrules text to soften absolutes: change the sentence about "Every async
route needs a sibling loading.tsx and error.tsx" to state that loading.tsx and
error.tsx are recommended route-segment UI/boundaries and that missing files
fall back to Next.js defaults; likewise modify the rules referencing "Server
Actions for mutations, not client-side API route calls" and "Never fetch in
useEffect" to use wording like "prefer Server Actions for mutations when
appropriate" and "prefer fetching in Server Components; avoid useEffect for data
fetching when possible," so the file mentions recommendation/preference rather
than strict prohibition for "loading.tsx"/"error.tsx", "Server Actions", and
"useEffect".

@oliviacraft
Copy link
Copy Markdown
Contributor Author

Hi! Just checking in on this PR. Happy to adjust the format if needed — let me know if there are any style requirements for new entries. Thanks for maintaining this resource!

@PatrickJS PatrickJS force-pushed the add-mdc-production-rules branch from bb84ab3 to ae4cd00 Compare June 1, 2026 00:15
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant