--- description: Enforces Next.js best practices for code organization, performance, security, and maintainability. This rule provides guidelines for structuring Next.js projects, optimizing performance, and avoiding common pitfalls. globs: **/*.{js,jsx,ts,tsx} --- - **General Principles** - **Use Static Generation (SSG) or Incremental Static Regeneration (ISR) where possible.** SSG offers the best performance by pre-rendering pages at build time. ISR allows you to update static pages after build time. - **Optimize Images.** Use `next/image` for automatic image optimization, including resizing, format conversion, and lazy loading. - **Utilize API Routes.** Create API endpoints using the `pages/api` directory for serverless functions. - **Follow a Consistent Component Structure.** Maintain a clear and predictable component structure for reusability and maintainability. - **Implement Code Splitting.** Split your code into smaller chunks using dynamic imports (`next/dynamic`) to improve initial load time. - **Lazy Load Non-Essential Resources.** Defer loading of resources that are not critical for the initial page load. - **Prefer Functional Programming and Immutable Data Structures.** This can improve code readability and reduce the risk of bugs. - **Handle Errors Robustly.** Implement comprehensive error handling and logging throughout your application. - **Code Organization and Structure** - **Directory Structure:** - `pages/`: Contains page components and API routes. - `components/`: Stores reusable UI components. - `styles/`: Holds global and component-specific CSS/SCSS modules. - `public/`: Static assets like images, fonts, and favicons. - `lib/` or `utils/`: Utility functions and helper modules. - `contexts/`: React Context providers for state management. - `hooks/`: Custom React hooks. - `types/` or `interfaces/`: TypeScript type definitions. - **File Naming Conventions:** - Use descriptive names for components and files (e.g., `ProductCard.tsx`, `useAuth.js`). - Employ camelCase for JavaScript filenames and PascalCase for component filenames. - Use kebab-case for CSS class names. - **Module Organization:** - Group related components and utilities into modules (e.g., `components/auth`, `utils/api`). - Export modules using named exports for better discoverability and tree-shaking. - **Component Architecture:** - Favor small, reusable components. - Use composition over inheritance. - Separate concerns by creating presentational (UI) and container (logic) components. - Utilize the `children` prop to create flexible and reusable components. - **Code Splitting Strategies:** - Use dynamic imports (`next/dynamic`) for large components or modules that are not critical for the initial page load. - Split code based on routes or user interactions. - Utilize Next.js's automatic code splitting. - **Common Patterns and Anti-patterns** - **Design Patterns:** - **Higher-Order Components (HOCs):** For cross-cutting concerns like authentication or data fetching. - **Render Props:** For sharing logic between components. - **Compound Components:** For creating complex UI elements with implicit state sharing. - **Recommended Approaches:** - **Data Fetching:** Use `getStaticProps`, `getServerSideProps`, or `getInitialProps` (legacy) for data fetching. - **State Management:** Consider using React Context, Zustand, Redux Toolkit, or Jotai for managing application state. - **Routing:** Utilize `next/link` for client-side navigation and `next/router` for programmatic routing. - **Anti-patterns:** - **Direct DOM Manipulation:** Avoid manipulating the DOM directly; use React's state and props instead. - **Global CSS Conflicts:** Use CSS Modules or CSS-in-JS to prevent style conflicts. - **Over-fetching Data:** Fetch only the data that is needed by the component. - **Unnecessary Re-renders:** Optimize component rendering using `React.memo` or `useMemo`. - **State Management Best Practices:** - Choose a state management solution that fits the complexity of your application. - Centralize state that is shared between multiple components. - Use immutable data structures to avoid unexpected side effects. - Use selectors to derive data from the state. - **Error Handling Patterns:** - Use `try...catch` blocks to handle errors gracefully. - Implement error boundaries to prevent crashes in production. - Log errors to a monitoring service for debugging. - Display user-friendly error messages. - **Performance Considerations** - **Optimization Techniques:** - **Minimize JavaScript Bundle Size:** Remove unused code, use tree-shaking, and compress your code. - **Optimize Third-Party Libraries:** Choose lightweight alternatives or lazy-load libraries. - **Cache API Responses:** Use caching to reduce the load on your API servers. - **Use a CDN:** Serve static assets from a Content Delivery Network (CDN). - **Memory Management:** - **Avoid Memory Leaks:** Clean up event listeners and timers when components unmount. - **Use Efficient Data Structures:** Choose data structures that are appropriate for the task. - **Rendering Optimization:** - **Use `React.memo`:** Prevent unnecessary re-renders of components. - **Virtualize Long Lists:** Render only the visible items in a long list to improve performance. - **Defer Expensive Calculations:** Use `useMemo` or `useCallback` to memoize expensive calculations. - **Bundle Size Optimization:** - **Analyze Bundle Size:** Use tools like `webpack-bundle-analyzer` to identify large dependencies. - **Remove Unused Dependencies:** Remove dependencies that are not being used. - **Use Code Splitting:** Split your code into smaller chunks to reduce initial load time. - **Lazy Loading Strategies:** - **Lazy Load Images:** Use `next/image` with the `lazy` loading prop. - **Lazy Load Components:** Use `next/dynamic` to lazy load components. - **Lazy Load Data:** Fetch data only when it is needed. - **Security Best Practices** - **Common Vulnerabilities:** - **Cross-Site Scripting (XSS):** Sanitize user input to prevent XSS attacks. - **Cross-Site Request Forgery (CSRF):** Use CSRF tokens to protect against CSRF attacks. - **SQL Injection:** Use parameterized queries or an ORM to prevent SQL injection attacks. - **Authentication and Authorization Vulnerabilities:** Implement secure authentication and authorization mechanisms. - **Input Validation:** - **Validate all user input:** Ensure that the input is of the expected type and format. - **Sanitize user input:** Remove or escape potentially harmful characters. - **Authentication and Authorization Patterns:** - **Use a secure authentication provider:** Consider using a third-party authentication provider like Auth0 or Firebase Authentication. - **Implement role-based access control (RBAC):** Restrict access to resources based on user roles. - **Use JSON Web Tokens (JWTs) for authentication:** JWTs are a secure and stateless way to authenticate users. - **Data Protection Strategies:** - **Encrypt sensitive data:** Encrypt data at rest and in transit. - **Use HTTPS:** Use HTTPS to encrypt communication between the client and server. - **Store passwords securely:** Use a strong hashing algorithm to store passwords. - **Secure API Communication:** - **Use API keys or tokens for authentication:** Require API keys or tokens for all API requests. - **Rate limit API requests:** Prevent abuse by limiting the number of requests that can be made from a single IP address. - **Validate API requests:** Ensure that the API requests are valid and authorized. - **Testing Approaches** - **Unit Testing Strategies:** - **Test individual components and functions in isolation.** - **Use mocking and stubbing to isolate dependencies.** - **Write tests for different scenarios and edge cases.** - **Integration Testing:** - **Test the interaction between multiple components or modules.** - **Test data flow and state management.** - **End-to-End Testing:** - **Test the entire application flow from the user's perspective.** - **Use tools like Cypress or Playwright for end-to-end testing.** - **Test Organization:** - **Keep tests close to the code they are testing.** - **Use a consistent naming convention for tests.** - **Organize tests into logical groups.** - **Mocking and Stubbing:** - **Use mocking to replace external dependencies with mock objects.** - **Use stubbing to replace functions with predefined return values.** - **Common Pitfalls and Gotchas** - **Frequent Mistakes:** - **Forgetting to handle errors.** - **Over-complicating state management.** - **Not optimizing images.** - **Not securing API routes.** - **Edge Cases:** - **Handling different screen sizes and devices.** - **Dealing with slow network connections.** - **Handling unexpected user input.** - **Version-Specific Issues:** - **Breaking changes in Next.js updates.** - **Compatibility issues with third-party libraries.** - **Compatibility Concerns:** - **Browser compatibility issues.** - **Accessibility issues.** - **Debugging Strategies:** - **Use the browser's developer tools to debug JavaScript code.** - **Use the Next.js devtools extension for debugging Next.js applications.** - **Use logging to track the flow of execution and identify errors.** - **Tooling and Environment** - **Recommended Development Tools:** - **VS Code:** A popular code editor with excellent support for JavaScript and TypeScript. - **ESLint:** A linter for identifying and fixing code style issues. - **Prettier:** A code formatter for automatically formatting code. - **Webpack Bundle Analyzer:** A tool for analyzing the size of your JavaScript bundles. - **Build Configuration:** - **Configure Webpack to optimize your code for production.** - **Use environment variables to configure your application for different environments.** - **Linting and Formatting:** - **Use ESLint and Prettier to enforce a consistent code style.** - **Configure your editor to automatically format code on save.** - **Deployment Best Practices:** - **Deploy your application to a platform like Vercel or Netlify.** - **Use environment variables to configure your application for production.** - **Monitor your application for errors and performance issues.** - **CI/CD Integration:** - **Use a CI/CD pipeline to automate the build, test, and deployment process.** - **Integrate your linting and formatting tools into your CI/CD pipeline.**