Next.Js AI Coding Rules

Next.Js AI rules help engineering teams get better results from AI coding assistants like Cursor, Windsurf, and GitHub Copilot. By defining clear conventions for code style, architecture patterns, error handling, and module organisation, Next.Js AI rules ensure that generated code is consistent, maintainable, and production-ready. Whether you are working on a side project or a large-scale enterprise system, community-curated rules on AI Rules Hub provide a solid foundation you can adopt instantly and customise to fit your team's standards.

Why Use AI Rules for Next.Js?

  • Ensure AI-generated Next.Js code follows your team's conventions
  • Prevent common anti-patterns that degrade maintainability
  • Reduce code review cycles by getting AI output right the first time
  • Standardise error handling, logging, and module structure
  • Make AI assistants produce secure and performance-conscious code

Best Practices for Next.Js AI Coding

Define a Consistent Code Style

Specify formatting preferences (indentation, quotes, trailing commas) for Next.Js so AI output matches your linter configuration without manual edits.

Enforce Error Handling Patterns

Instruct AI to always handle errors explicitly, use structured logging, and avoid swallowing exceptions silently.

Set Module Organisation Rules

Define how Next.Js modules should be organised — feature folders, barrel exports, and separation of concerns — so AI keeps the project structure clean.

Require Security-Conscious Patterns

Add rules that enforce input validation, sanitisation, and safe dependency usage so AI never introduces obvious security vulnerabilities.

Common Patterns & Standards

#01

Separation of Concerns

Keep business logic, data access, and presentation layers separate in Next.Js projects so each layer is independently testable.

#02

Dependency Injection

Pass dependencies explicitly through constructors or function parameters — avoiding global state that makes testing difficult.

#03

Consistent Naming Conventions

Rule AI to follow Next.Js community naming standards for files, classes, functions, and constants.

#04

Automated Testing Standards

Define what test types are required (unit, integration) and where test files should live so AI generates tests alongside implementation code.

Top Next.Js Rules on AI Rules Hub

No description provided.

## **Core Principles**

* Use server-first architecture; prefer server components unless client-side behavior is required.
* Maintain strict separation of concerns across UI, business logic, and data layers.
* Ensure all code is scalable, modular, and maintainable.

---

## **Data Fetching Rules**

* Do not call `fetch()` directly inside components.
* All API communication must be handled through a centralized HTTP client.
* API logic must exist only in the `services` layer.
* UI components must access data only through hooks.

---

## **Component Rules**

* Each component must have a single responsibility.
* Component files must not exceed 150 lines.
* Target component size should be between 50–80 lines.
* Large components must be split into smaller reusable components.

---

## **State Management Rules**

* Use a centralized state management solution (e.g., Zustand or Redux Toolkit).
* Do not use `useContext` for global state management.
* Keep global state minimal and domain-specific.

---

## **Forms & Validation Rules**

* All forms must use a structured form library (e.g., React Hook Form).
* All validation must be schema-based (e.g., Zod).
* Validation schemas must be reusable and stored separately.

---

## **TypeScript Rules**

* Strict TypeScript is mandatory.
* Do not use `any` type.
* All API responses must use a generic structure (e.g., `ApiResponse<T>`).
* Types must be defined and reused across the application.

---

## **Routing Rules**

* All routes must be centralized in a constants file.
* Do not hardcode route paths inside components or navigation logic.

---

## **Enums & Constants Rules**

* Do not hardcode strings such as roles, statuses, or API identifiers.
* All enums must be defined in a centralized location.
* Reuse enums across all features.

---

## **Directory Structure Rules**

* Follow feature-based architecture:

```
src/
  features/
    [feature]/
      components/
      services/
      hooks/
      types/
      schemas/

  components/ui/
  store/
  lib/
  constants/
  types/enums/
```

---

## **Layer Responsibilities**

* UI layer must handle rendering only.
* Hooks must handle business logic and data orchestration.
* Services must handle API communication.
* Store must handle global state only.
* Schemas must handle validation.
* Types must define contracts and interfaces.

---

## **Prohibited Practices**

* Do not call APIs directly inside UI components.
* Do not use `fetch()` directly.
* Do not hardcode routes or static strings.
* Do not create large monolithic components.
* Do not use `any` in TypeScript.

---

## **Architecture Philosophy**

* Build systems, not pages.
* Prioritize consistency over flexibility.
* Ensure every module is reusable and replaceable.
* Maintain clear boundaries between layers.

---

## **Compatibility**

* This rule set is designed for modern frontend stacks (React, Next.js, TanStack, etc.).
* Aligns with standardized rule-sharing ecosystems like Airuleshub .
7 views

No description provided.

# Next.js SSR Project Development Rules

These rules define the architecture and coding standards for this
Next.js project.

Supported AI IDEs: - Cursor - Windsurf - GitHub Copilot - VS Code AI
tools - JetBrains AI Assistant

Framework: Next.js (App Router) Language: TypeScript Rendering: Server
Components + SSR

------------------------------------------------------------------------

# Core Principles

Always prioritize:

1.  Server Components
2.  SSR data fetching
3.  Type safety
4.  Separation of concerns
5.  Scalable folder structure

Avoid unnecessary client components.

------------------------------------------------------------------------

# Project Folder Structure

Use the following structure.

app/ (api)/ (auth)/ dashboard/ layout.tsx page.tsx

components/ ui/ forms/ shared/

services/ api/ server/

lib/ db/ auth/ config/

hooks/ types/ utils/ constants/ styles/

Rules: - UI components → components/ - API communication →
services/api - Server logic → services/server - Shared utilities →
utils - Types → types

------------------------------------------------------------------------

# Rendering Rules

Default behavior must be Server Components.

Example:

``` tsx
export default async function Page() {
  const users = await getUsers()

  return (
    <div>
      {users.map(user => (
        <p key={user.id}>{user.name}</p>
      ))}
    </div>
  )
}
```

Only use client components when needed.

Client component must start with:

"use client"

------------------------------------------------------------------------

# SSR Data Fetching Rules

Always fetch data on the server.

Example:

``` ts
async function getUsers() {
  const res = await fetch("https://api.example.com/users", {
    cache: "no-store"
  })

  return res.json()
}
```

Rules: - Prefer fetch() inside server components - Use revalidate for
caching - Avoid client-side API calls unless required

------------------------------------------------------------------------

# Server Actions Rules

Use Server Actions for mutations.

Example:

``` ts
"use server"

export async function createUser(formData: FormData) {
  const name = formData.get("name")

  await db.user.create({
    data: { name }
  })
}
```

Rules: - All mutations must be server actions - Never expose secrets to
client components

------------------------------------------------------------------------

# API Route Rules

Location:

app/api/

Example:

app/api/users/route.ts

Example API handler:

``` ts
export async function GET() {
  return Response.json({ success: true })
}
```

Rules: - API routes should only contain request handling - Business
logic must live in services

------------------------------------------------------------------------

# Component Rules

Component guidelines: - Functional components only - Keep components
small - Separate UI and logic

Example:

components/UserCard.tsx

Example:

``` tsx
type Props = {
  name: string
}

export function UserCard({ name }: Props) {
  return <div>{name}</div>
}
```

------------------------------------------------------------------------

# TypeScript Rules

Strict TypeScript must be used.

Never use: any

Always type: - Props - API responses - Services

Example:

``` ts
type User = {
  id: string
  name: string
  email: string
}
```

------------------------------------------------------------------------

# Service Layer Rules

All API logic must live in services.

Example structure:

services/ api/ userService.ts authService.ts

Example:

``` ts
export async function getUsers(): Promise<User[]> {
  const res = await fetch("/api/users")
  return res.json()
}
```

Rules: - UI components must not call APIs directly - Use service
functions

------------------------------------------------------------------------

# SEO Rules

Always use Next.js metadata API.

Example:

``` ts
export const metadata = {
  title: "Dashboard",
  description: "User dashboard"
}
```

------------------------------------------------------------------------

# Performance Rules

Always use built-in Next.js optimizations.

Required tools: - next/image - next/font - dynamic imports

Example:

``` tsx
import Image from "next/image"
```

------------------------------------------------------------------------

# Environment Variables

Secrets must live in:

.env.local

Example:

DATABASE_URL= NEXT_PUBLIC_API_URL= JWT_SECRET=

Rules: - Server secrets must never be exposed to client components

------------------------------------------------------------------------

# Error Handling

Use proper error boundaries.

Example:

app/error.tsx

Example:

``` tsx
export default function Error({ error }) {
  return <div>Something went wrong</div>
}
```

------------------------------------------------------------------------

# Naming Conventions

Components → PascalCase Hooks → camelCase starting with use Services →
camelCase

Examples: UserCard.tsx useAuth.ts userService.ts formatPrice.ts

------------------------------------------------------------------------

# Testing Rules

Testing tools: - Jest - React Testing Library

Example test file:

UserCard.test.tsx

------------------------------------------------------------------------

# Code Quality Rules

Never: - Use any - Put business logic inside UI - Fetch data inside
client components unnecessarily - Duplicate logic

Always: - Write reusable components - Use proper types - Follow folder
structure - Keep components small
14 views

Best practices to improve web performance and Lighthouse score.

When writing frontend code, follow these performance rules:

1. Reduce JavaScript bundle size.

2. Lazy load components when possible.

3. Use code splitting.

4. Avoid unnecessary state updates.

5. Debounce expensive operations.

6. Optimize images and use modern formats (WebP).

7. Avoid blocking scripts.

8. Use memoization for heavy computations.

9. Reduce DOM nodes where possible.

10. Ensure Lighthouse performance score stays above 90.
11 views

Rules to ensure scalable, performant, and maintainable Next.js applications.

You are an expert Next.js developer. Follow these rules when generating or modifying code:

1. Always prefer Server Components in Next.js unless client-side interactivity is required.

2. Use the App Router structure and organize files by feature:
   /app
   /components
   /lib
   /hooks
   /services

3. Avoid unnecessary client-side JavaScript. Use "use client" only when required.

4. Optimize images using next/image.

5. Use dynamic imports for heavy components to reduce bundle size.

6. Always implement loading.tsx and error.tsx for routes.

7. Follow SEO best practices using metadata API.

8. Avoid inline styles; prefer Tailwind or CSS modules.

9. Ensure accessibility (aria labels, semantic HTML).

10. Optimize performance by reducing main-thread work and avoiding heavy libraries.

Always prioritize performance, readability, and scalability.
6 views

Share Your Next.Js AI Rules

Have rules that improved your Next.Js workflow? Submit them to AI Rules Hub and help the community get better results from AI coding assistants.

Frequently Asked Questions

Next.Js AI rules are context files (like `.cursorrules` or `AGENTS.md`) that instruct AI coding assistants to follow Next.Js best practices — covering code style, architecture, error handling, and testing conventions.

Command Palette

Search for a command to run...