Skip to content

Latest commit

 

History

History
105 lines (82 loc) · 7.33 KB

react-nextjs-ts.md

File metadata and controls

105 lines (82 loc) · 7.33 KB

Export Style and Module Organization

  • All exports must be named exports. Default exports are forbidden except in Next.js page.tsx and layout.tsx files only.
  • Import paths must use absolute imports from tsconfig.json aliases (@/components, @/lib, @/hooks). Relative imports beyond ../ are forbidden.
  • Each file exports exactly one thing (one component, one hook, one utility function). Multi-export files are forbidden except for type definition files ending in .types.ts.
  • Barrel exports (index.ts re-exporting from sibling files) are forbidden. Import directly from the source file.

File Naming and Location

  • React components live in app/components/ and must be PascalCase with .tsx extension.
  • Custom hooks live in app/hooks/ and must be named useXxx.ts with camelCase.
  • Utility functions live in lib/ and must be camelCase with .ts extension.
  • API routes live in app/api/ following Next.js App Router conventions. No pages/api/ allowed.
  • Database queries and mutations live in lib/db/ and must be named with verb prefix: getUser.ts, createPost.ts, updateProfile.ts.
  • Server actions live in app/actions/ and must be named with verb prefix: submitForm.ts, deleteItem.ts.
  • Type definitions live in lib/types/ and must end in .types.ts.
  • Tests live adjacent to source files with .test.ts or .test.tsx extension. No separate tests/ directories.

TypeScript Type Safety

  • Never use any type. If the shape is unknown, use unknown and narrow with type guards.
  • Never use as type assertions outside of .test.ts files. Use type guards, Zod .parse(), or satisfies operator instead.
  • All function parameters must have explicit types. Implicit any is forbidden.
  • All function return types must be explicit except for arrow functions with single-line returns that are obvious (e.g., const double = (x: number) => x * 2).
  • React component props must be defined as a single Props interface exported from the same file.
  • All async functions must explicitly return Promise, never Promise.

Data Fetching and Server/Client Boundaries

  • Data fetching must happen in Server Components or Server Actions. Never fetch in useEffect.
  • useEffect is forbidden for data fetching. Use Server Components, Server Actions, or SWR/React Query in Client Components only.
  • All Client Components must have "use client" directive at the top of the file.
  • All Server Components must NOT have "use client" directive.
  • API calls from Client Components must go through /app/api/ routes, never directly to external services.
  • Database clients (Supabase, Prisma, etc.) must be imported from lib/db/client.ts singleton. Creating new clients inline is forbidden.
  • Every async data-fetching component must render Suspense boundaries with fallback UI. Skeleton components must exist for every async component.

Error Handling

  • Every async function must have try/catch. Caught errors must be typed: catch (err) { if (err instanceof AppError)... } — never catch (e: any).
  • All errors must be instances of a custom error class extending Error (e.g., AppError, ValidationError, NotFoundError).
  • Error messages must never expose internal implementation details or stack traces to the client.
  • Server Actions must return { success: boolean; error?: string; data?: T } structure. Never throw directly from Server Actions.
  • API routes must return { success: boolean; error?: string; data?: T } structure with appropriate HTTP status codes.
  • All form submissions must handle errors and display them to the user. No silent failures.

Security

  • Environment variables used in the browser must be prefixed with NEXT_PUBLIC_. All other env vars are server-only.
  • No hardcoded API keys, tokens, or secrets anywhere in the codebase. All must come from environment variables.
  • All user input from forms, query params, and request bodies must be validated with Zod schemas before use.
  • Database queries must use parameterized queries or ORM methods. String concatenation for SQL is forbidden.
  • Sensitive operations (auth, payments, admin actions) must be in Server Actions or API routes, never in Client Components.
  • CORS headers must be explicitly set in API routes. Never use wildcard (*) for Access-Control-Allow-Origin in production.

React Component Patterns

  • All components must be functional components. Class components are forbidden.
  • useState must only store UI state (open/closed, form values, selected tab). Never store derived or fetched data in useState.
  • useCallback must wrap all functions passed as props to memoized children. Inline function props are forbidden.
  • useMemo must wrap expensive computations passed as props. Inline object/array literals as props are forbidden.
  • All components must have explicit prop types via Props interface. Destructuring without types is forbidden.
  • Loading, error, and empty states must be rendered explicitly. Never render null or undefined without a fallback.
  • Conditional rendering must use early returns or ternary operators. Never use && operators for rendering.

Form Handling

  • All forms must use controlled components (value + onChange). Uncontrolled forms are forbidden.
  • Form validation must use Zod schemas. Inline validation logic is forbidden.
  • Form submission must be a Server Action. Client-side form submission to API routes is forbidden.
  • All form fields must have error messages displayed below the field. Missing error UI is forbidden.
  • All form buttons must be disabled during submission. Never allow double-submission.

Testing

  • Every utility function in lib/ must have a .test.ts file with at least 3 test cases covering happy path, error case, and edge case.
  • Every custom hook must have a .test.tsx file using @testing-library/react-hooks.
  • Every Server Action must have a .test.ts file mocking the database layer.
  • Test files must use describe() blocks organized by function name.
  • Test names must start with "should" and describe the expected behavior: "should return user when id exists".
  • Never mock React or Next.js internals. Mock only external dependencies (database, API calls, auth).

Naming Conventions

  • Boolean variables and functions must start with is, has, can, or should: isLoading, hasError, canDelete, shouldRender.
  • Event handlers must be named on + PascalCase: onClick, onSubmit, onUserSelect.
  • Server Actions must be named with verb prefix: submitForm, deletePost, updateProfile.
  • Zod schemas must be named SchemaNameSchema: UserSchema, CreatePostSchema.
  • Constants must be UPPER_SNAKE_CASE and live at the top of the file or in lib/constants/.
  • Magic numbers and strings are forbidden. Extract to named constants.

Next.js App Router Specifics

  • All routes must use App Router (app/ directory). Pages Router (pages/ directory) is forbidden.
  • Route segments must be lowercase with hyphens: app/user-profile/, app/admin-dashboard/. No camelCase or underscores.
  • Dynamic routes must use [id] syntax. Catch-all routes [...slug] are forbidden unless explicitly needed.
  • Layout files must be named layout.tsx and export a default component.
  • Page files must be named page.tsx and export a default component.
  • Metadata must be defined via generateMetadata() function or metadata export. Never use Head component.

Source: Codelibrium — the marketplace for AI behaviour files. Browse multiple rulesets at codelibrium.com or install via CLI: npx codelibrium-cli install <ruleset-name>