mirror of
https://github.com/sanjeed5/awesome-cursor-rules-mdc.git
synced 2026-11-30 14:52:55 +08:00
Add comprehensive MDC files for various technologies and frameworks
Generate a large set of Markdown Configuration (MDC) files covering best practices across multiple domains, including: - AI/ML libraries (PyTorch, TensorFlow, scikit-learn) - Backend frameworks (Django, FastAPI, Express, Spring Boot) - Frontend frameworks (React, Vue, Angular) - Cloud platforms (AWS, Azure, GCP) - Development tools (Docker, Kubernetes, Terraform) - State management libraries - UI component libraries - Web technologies and APIs Enhance project documentation with detailed, standardized best practice guidelines for different technologies and frameworks
This commit is contained in:
@@ -0,0 +1,178 @@
|
||||
---
|
||||
description: This rule provides comprehensive best practices for using Apollo Client in your projects, covering code organization, performance, security, testing, and common pitfalls. It aims to guide developers in building robust and maintainable GraphQL-powered applications.
|
||||
globs: **/*.{js,jsx,ts,tsx,gql,graphql}
|
||||
---
|
||||
- **Code Organization and Structure:**
|
||||
- **Directory Structure:**
|
||||
- Organize GraphQL queries and mutations in a dedicated directory (e.g., `graphql` or `queries`).
|
||||
- Group related queries and mutations into subdirectories based on features or modules.
|
||||
- Consider a separate directory for GraphQL types/schemas if you're managing them locally.
|
||||
- Example:
|
||||
|
||||
src/
|
||||
graphql/
|
||||
user/
|
||||
getUser.gql
|
||||
createUser.gql
|
||||
product/
|
||||
getProduct.gql
|
||||
updateProduct.gql
|
||||
|
||||
- **File Naming Conventions:**
|
||||
- Use descriptive names for GraphQL query and mutation files (e.g., `getUser.gql`, `updateProduct.gql`).
|
||||
- Employ a consistent naming scheme (e.g., `[operationName].[operationType].gql`).
|
||||
- **Module Organization:**
|
||||
- Encapsulate Apollo Client logic (e.g., initialization, hooks) within reusable modules.
|
||||
- Create custom hooks for common data fetching patterns (e.g., `useUser`, `useProduct`).
|
||||
- **Component Architecture:**
|
||||
- Favor a component-based architecture for UI development.
|
||||
- Decouple data fetching logic from UI components using hooks or render props.
|
||||
- Utilize higher-order components (HOCs) or render props for cross-cutting concerns (e.g., authentication, error handling).
|
||||
- **Code Splitting:**
|
||||
- Use dynamic imports to lazy-load components and queries, improving initial load time.
|
||||
- Split large queries into smaller fragments to reduce bundle size.
|
||||
|
||||
- **Common Patterns and Anti-patterns:**
|
||||
- **Design Patterns:**
|
||||
- **Repository Pattern:** Abstract data access logic behind a repository interface.
|
||||
- **Facade Pattern:** Provide a simplified interface to a complex subsystem (e.g., Apollo Client).
|
||||
- **Hook Composition:** Combine multiple custom hooks to create more complex data fetching logic.
|
||||
- **Recommended Approaches:**
|
||||
- Use the `useQuery` and `useMutation` hooks for data fetching and manipulation.
|
||||
- Leverage Apollo Client's cache for improved performance and offline capabilities.
|
||||
- Implement optimistic updates to provide a better user experience.
|
||||
- Use GraphQL fragments to reuse common data structures across multiple queries and mutations.
|
||||
- **Anti-patterns:**
|
||||
- Avoid directly manipulating the Apollo Client cache outside of mutations.
|
||||
- Don't fetch the entire schema unnecessarily; only fetch what you need.
|
||||
- Avoid deeply nested components with complex data fetching logic.
|
||||
- **State Management:**
|
||||
- Use Apollo Client's cache as the primary source of truth for application state.
|
||||
- Integrate with external state management libraries (e.g., Redux, Zustand) when necessary for complex state requirements.
|
||||
- Consider using Apollo Link State for managing local client-side state.
|
||||
- **Error Handling:**
|
||||
- Implement global error handling with Apollo Link.
|
||||
- Display user-friendly error messages to the user.
|
||||
- Retry failed queries or mutations automatically.
|
||||
|
||||
- **Performance Considerations:**
|
||||
- **Optimization Techniques:**
|
||||
- Use the `fetchPolicy` option in `useQuery` to control cache behavior.
|
||||
- Implement pagination for large datasets.
|
||||
- Use batching and caching at the server-side to reduce network requests.
|
||||
- **Memory Management:**
|
||||
- Unsubscribe from subscriptions when components unmount to prevent memory leaks.
|
||||
- Avoid storing large amounts of data in the Apollo Client cache.
|
||||
- **Rendering Optimization:**
|
||||
- Use React's `memo` or `useMemo` to prevent unnecessary re-renders.
|
||||
- Implement virtualization for rendering large lists.
|
||||
- **Bundle Size Optimization:**
|
||||
- Use code splitting to reduce the initial bundle size.
|
||||
- Remove unused dependencies.
|
||||
- Minify and compress your code.
|
||||
- **Lazy Loading:**
|
||||
- Lazy-load components and queries using dynamic imports.
|
||||
|
||||
- **Security Best Practices:**
|
||||
- **Common Vulnerabilities:**
|
||||
- **GraphQL Injection:** Prevent injection attacks by validating user input and using parameterized queries.
|
||||
- **Denial of Service (DoS):** Limit query complexity and depth to prevent DoS attacks.
|
||||
- **Information Disclosure:** Avoid exposing sensitive data in error messages.
|
||||
- **Input Validation:**
|
||||
- Validate all user input on both the client and server sides.
|
||||
- Use GraphQL's built-in validation capabilities.
|
||||
- **Authentication and Authorization:**
|
||||
- Implement proper authentication and authorization mechanisms.
|
||||
- Use JWT (JSON Web Tokens) or other secure authentication protocols.
|
||||
- Follow the principle of least privilege when granting access to data.
|
||||
- **Data Protection:**
|
||||
- Encrypt sensitive data at rest and in transit.
|
||||
- Use HTTPS for all API communication.
|
||||
- **Secure API Communication:**
|
||||
- Use Apollo Link to add security headers to API requests.
|
||||
- Implement CORS (Cross-Origin Resource Sharing) to prevent cross-site scripting (XSS) attacks.
|
||||
|
||||
- **Testing Approaches:**
|
||||
- **Unit Testing:**
|
||||
- Test individual components and hooks in isolation.
|
||||
- Mock Apollo Client's API to control data fetching behavior.
|
||||
- **Integration Testing:**
|
||||
- Test the integration of components with Apollo Client.
|
||||
- Use a test GraphQL server to simulate real API interactions.
|
||||
- **End-to-end Testing:**
|
||||
- Test the entire application flow from the user interface to the backend.
|
||||
- Use tools like Cypress or Puppeteer for end-to-end testing.
|
||||
- **Test Organization:**
|
||||
- Organize tests in a directory structure that mirrors the source code.
|
||||
- Use descriptive names for test files and test cases.
|
||||
- **Mocking and Stubbing:**
|
||||
- Use mocking libraries (e.g., Jest, Sinon) to mock Apollo Client's API.
|
||||
- Create stub GraphQL responses for testing different scenarios.
|
||||
|
||||
- **Common Pitfalls and Gotchas:**
|
||||
- **Frequent Mistakes:**
|
||||
- Incorrect cache configuration leading to stale data.
|
||||
- Over-fetching data in GraphQL queries.
|
||||
- Ignoring error handling in `useQuery` and `useMutation`.
|
||||
- **Edge Cases:**
|
||||
- Handling network errors and offline scenarios.
|
||||
- Dealing with large datasets and complex queries.
|
||||
- Managing cache invalidation and updates.
|
||||
- **Version-Specific Issues:**
|
||||
- Be aware of breaking changes between Apollo Client versions.
|
||||
- Consult the Apollo Client documentation for migration guides.
|
||||
- **Compatibility Concerns:**
|
||||
- Ensure compatibility with different browsers and devices.
|
||||
- Test your application on different platforms.
|
||||
- **Debugging Strategies:**
|
||||
- Use Apollo Client DevTools to inspect queries, mutations, and cache state.
|
||||
- Log API requests and responses for debugging purposes.
|
||||
|
||||
- **Tooling and Environment:**
|
||||
- **Recommended Tools:**
|
||||
- Apollo Client DevTools for debugging and inspecting the cache.
|
||||
- GraphQL Playground or GraphiQL for exploring and testing GraphQL APIs.
|
||||
- Apollo VS Code extension for syntax highlighting and autocompletion.
|
||||
- **Build Configuration:**
|
||||
- Use a build tool like Webpack or Parcel to bundle your code.
|
||||
- Configure Babel to transpile your code to compatible JavaScript versions.
|
||||
- **Linting and Formatting:**
|
||||
- Use ESLint and Prettier to enforce code style and best practices.
|
||||
- Configure linting rules specific to Apollo Client and GraphQL.
|
||||
- **Deployment:**
|
||||
- Use a deployment platform like Netlify, Vercel, or AWS Amplify.
|
||||
- Configure environment variables for API endpoints and other sensitive data.
|
||||
- **CI/CD Integration:**
|
||||
- Use a CI/CD pipeline to automate testing and deployment.
|
||||
- Integrate linters, formatters, and test runners into the pipeline.
|
||||
|
||||
- **Specific Best Practices based on Exa Search Results:**
|
||||
- Ensure all queries for a specific type return an ID for normalization and caching (RedwoodJS Community).
|
||||
- Store queries in separate `.gql` files and use tools like `graphql-import` for better organization (Reddit).
|
||||
- Use Apollo Client's `watchQuery` method for real-time data updates (Medium).
|
||||
- Follow GraphQL query best practices for efficient API design (Apollo GraphQL).
|
||||
|
||||
- **Additional considerations**
|
||||
- When creating queries and mutations, follow best practices to get the most out of both GraphQL and Apollo tooling.
|
||||
|
||||
- **Example Directory Structure**
|
||||
|
||||
src/
|
||||
components/
|
||||
UserCard.tsx
|
||||
ProductDetails.tsx
|
||||
graphql/
|
||||
queries/
|
||||
getUser.gql
|
||||
getProduct.gql
|
||||
mutations/
|
||||
createUser.gql
|
||||
updateProduct.gql
|
||||
hooks/
|
||||
useUser.ts
|
||||
useProduct.ts
|
||||
utils/
|
||||
apolloClient.ts // Initialize Apollo Client here
|
||||
|
||||
|
||||
This is a comprehensive guide for using Apollo Client. Please adapt these guidelines to your specific project requirements and coding style.
|
||||
@@ -0,0 +1,55 @@
|
||||
---
|
||||
description: This rule provides comprehensive best practices and coding standards for GraphQL development, covering code organization, performance, security, testing, and common pitfalls.
|
||||
globs: **/*.graphql
|
||||
---
|
||||
- **Naming Conventions**:
|
||||
- Use `camelCase` for field names, argument names, and directive names. This is a widely accepted convention that enhances readability and consistency.
|
||||
- Use the suffix `Input` when naming input types (e.g., `UserInput`). This clearly distinguishes input types from other types in your schema.
|
||||
- Avoid verb prefixes like `get` in field names (e.g., use `users` instead of `getUsers`). This maintains clarity and consistency in your schema.
|
||||
|
||||
- **Schema Design and Query Optimization**:
|
||||
- Design your schema to prevent over-fetching or under-fetching of data. Use fragments to request only the necessary data.
|
||||
- Use variables for parameters instead of hard-coded values. This enhances flexibility and maintainability, and allows for query caching.
|
||||
- Implement pagination for large datasets to avoid overwhelming the client and improve performance.
|
||||
- Use field aliases to rename fields in the response, which can be useful for backward compatibility or to simplify the client-side code.
|
||||
|
||||
- **Code Organization and Structure**:
|
||||
- **Directory Structure**: Organize your GraphQL schema files into a logical directory structure. Consider grouping related types and resolvers together (e.g., `schemas/user/`, `resolvers/user/`).
|
||||
- **File Naming Conventions**: Use descriptive names for schema files (e.g., `user.graphql`, `product.graphql`).
|
||||
- **Module Organization**: Break down your schema into smaller, reusable modules. Use schema stitching or federation to combine these modules into a single API.
|
||||
- **Component Architecture**: If using a GraphQL client library like Apollo Client or Relay, structure your components to efficiently manage GraphQL queries and data fetching.
|
||||
|
||||
- **Common Patterns and Anti-patterns**:
|
||||
- **Design Patterns**: Consider using patterns like the Facade pattern to simplify complex resolvers or the DataLoader pattern to batch and cache data fetching.
|
||||
- **Anti-patterns**: Avoid creating overly complex queries that fetch too much data in a single request. Also avoid using deeply nested resolvers, as this can lead to performance issues.
|
||||
- **State Management**: Choose a state management solution that integrates well with your GraphQL client library. Consider using Apollo Client's cache or Relay's store for client-side data management.
|
||||
- **Error Handling**: Implement robust error handling in your resolvers. Return user-friendly error messages and log detailed error information on the server.
|
||||
|
||||
- **Performance Considerations**:
|
||||
- **Optimization Techniques**: Use techniques like query batching, caching, and persisted queries to optimize performance.
|
||||
- **Memory Management**: Be mindful of memory usage in your resolvers, especially when dealing with large datasets.
|
||||
- **Lazy Loading**: Implement lazy loading for non-critical data to improve initial page load times.
|
||||
|
||||
- **Security Best Practices**:
|
||||
- **Input Validation**: Validate all user inputs to prevent injection attacks and other security vulnerabilities. Use appropriate data types and constraints in your schema.
|
||||
- **Authentication and Authorization**: Implement strong authentication and authorization mechanisms to protect your API. Use role-based access control (RBAC) to restrict access to sensitive data.
|
||||
- **Data Protection**: Protect sensitive data by encrypting it at rest and in transit. Use HTTPS to secure API communication.
|
||||
- **Rate Limiting**: Implement rate limiting to prevent denial-of-service (DoS) attacks.
|
||||
- **Query Complexity Analysis**: Limit the complexity of GraphQL queries to prevent malicious users from overloading the server. Tools like `graphql-cost-analysis` can help.
|
||||
|
||||
- **Testing Approaches**:
|
||||
- **Unit Testing**: Write unit tests for your resolvers to ensure they are functioning correctly.
|
||||
- **Integration Testing**: Write integration tests to verify that your GraphQL API integrates correctly with your data sources and other services.
|
||||
- **End-to-end Testing**: Write end-to-end tests to simulate user interactions with your API and verify that the entire system is working as expected.
|
||||
- **Test Organization**: Organize your tests into a logical directory structure. Use clear and descriptive names for your test files.
|
||||
- **Mocking and Stubbing**: Use mocking and stubbing to isolate your resolvers from external dependencies during testing.
|
||||
|
||||
- **Common Pitfalls and Gotchas**:
|
||||
- **N+1 Problem**: Be aware of the N+1 problem, where fetching a list of items requires N additional queries to fetch related data. Use DataLoader to batch and cache these queries.
|
||||
- **Circular Dependencies**: Avoid circular dependencies between your schema types, as this can lead to errors.
|
||||
|
||||
- **Tooling and Environment**:
|
||||
- **Recommended Development Tools**: Use tools like GraphQL Playground or GraphiQL for exploring and testing your API. Consider using a GraphQL IDE like Apollo Studio or Altair GraphQL Client for advanced features.
|
||||
- **Linting and Formatting**: Use a GraphQL linter and formatter to enforce code style and prevent errors. Consider using ESLint with the `eslint-plugin-graphql` plugin.
|
||||
- **Deployment Best Practices**: Deploy your GraphQL API behind a CDN to improve performance and availability. Use a GraphQL gateway to manage authentication, authorization, and rate limiting.
|
||||
- **CI/CD Integration**: Integrate your GraphQL API into your CI/CD pipeline to automate testing and deployment.
|
||||
@@ -0,0 +1,185 @@
|
||||
---
|
||||
description: This rule provides comprehensive guidelines for using Axios effectively, covering best practices, security considerations, and performance optimization. It aims to improve code quality, maintainability, and overall application resilience when working with Axios.
|
||||
globs: **/*.{js,jsx,ts,tsx}
|
||||
---
|
||||
- **Avoid hardcoding URLs**: Store API endpoints in configuration files or environment variables to enhance maintainability and avoid redundancy.
|
||||
- **Centralize API Logic**: Create dedicated modules or services to encapsulate Axios instances and request logic. This promotes reusability and simplifies debugging.
|
||||
- **Handle Errors Gracefully**: Implement comprehensive error handling using try-catch blocks, response interceptors, and centralized error logging. Display user-friendly error messages.
|
||||
- **Use Asynchronous Functions**: Leverage `async/await` or Promises for cleaner and more manageable asynchronous code when making Axios requests.
|
||||
- **Optimize with Request Interceptors**: Utilize request interceptors for tasks like adding authentication tokens, logging requests, or transforming request data. Response interceptors can be used for error handling or data transformation.
|
||||
- **Ensure HTTP Requests When Necessary**: Verify that requests are only made when truly needed, preventing unnecessary network traffic and improving performance. Consider caching strategies.
|
||||
|
||||
### 1. Code Organization and Structure:
|
||||
|
||||
- **Directory Structure Best Practices**:
|
||||
- Create an `api` or `services` directory to house all API-related code.
|
||||
- Organize API modules based on resources or features (e.g., `api/users.js`, `api/products.js`).
|
||||
- Separate Axios instance configuration into a dedicated file (e.g., `api/axios-config.js`).
|
||||
|
||||
- **File Naming Conventions**:
|
||||
- Use descriptive names for API modules (e.g., `userApi.js`, `productService.js`).
|
||||
- Follow a consistent naming convention (e.g., camelCase for variables, PascalCase for components).
|
||||
|
||||
- **Module Organization**:
|
||||
- Export individual API functions from each module (e.g., `getUser`, `createUser`).
|
||||
- Use named exports for better code readability and maintainability.
|
||||
|
||||
- **Component Architecture**:
|
||||
- Create reusable components for handling data fetching and display.
|
||||
- Decouple components from specific API calls to improve reusability.
|
||||
- Utilize custom hooks to encapsulate data fetching logic.
|
||||
|
||||
- **Code Splitting Strategies**:
|
||||
- Implement lazy loading for API modules that are not immediately required.
|
||||
- Use dynamic imports to load modules on demand.
|
||||
- Consider route-based code splitting for larger applications.
|
||||
|
||||
### 2. Common Patterns and Anti-patterns:
|
||||
|
||||
- **Design Patterns Specific to Axios**:
|
||||
- **Singleton Pattern**: Use a singleton pattern for the Axios instance to ensure a single configuration across the application.
|
||||
- **Adapter Pattern**: Create an adapter layer to transform API responses into a consistent format.
|
||||
- **Factory Pattern**: Use a factory pattern to create different Axios instances with specific configurations.
|
||||
|
||||
- **Recommended Approaches for Common Tasks**:
|
||||
- **Authentication**: Use request interceptors to add authentication headers (e.g., JWT tokens).
|
||||
- **Error Handling**: Implement a centralized error handling function to log errors and display user-friendly messages.
|
||||
- **Data Transformation**: Use response interceptors to transform data before it reaches the components.
|
||||
|
||||
- **Anti-patterns and Code Smells to Avoid**:
|
||||
- **Hardcoding URLs**: Avoid hardcoding API endpoints directly in the code.
|
||||
- **Duplicated Request Logic**: Don't repeat API request logic across multiple components.
|
||||
- **Ignoring Errors**: Never ignore errors returned by Axios; always handle them appropriately.
|
||||
|
||||
- **State Management Best Practices**:
|
||||
- Use a state management library (e.g., Redux, Zustand, Recoil) to manage API data.
|
||||
- Store API responses in a normalized format to improve performance.
|
||||
- Utilize selectors to derive data from the store efficiently.
|
||||
|
||||
- **Error Handling Patterns**:
|
||||
- Implement a global error boundary to catch unexpected errors.
|
||||
- Display user-friendly error messages based on the error type.
|
||||
- Log errors to a central logging service for monitoring and debugging.
|
||||
|
||||
### 3. Performance Considerations:
|
||||
|
||||
- **Optimization Techniques**:
|
||||
- **Caching**: Implement caching mechanisms to avoid redundant API calls.
|
||||
- **Request Debouncing**: Debounce frequent API requests to reduce server load.
|
||||
- **Request Cancellation**: Cancel pending requests when the component unmounts or the user navigates away.
|
||||
|
||||
- **Memory Management**:
|
||||
- Clear Axios instances when they are no longer needed.
|
||||
- Avoid creating unnecessary Axios instances.
|
||||
|
||||
- **Rendering Optimization**:
|
||||
- Use memoization techniques to prevent unnecessary re-renders.
|
||||
- Implement pagination or virtualized lists for large datasets.
|
||||
|
||||
- **Bundle Size Optimization**:
|
||||
- Use tree shaking to remove unused code from the Axios library.
|
||||
- Minify and compress the JavaScript bundle.
|
||||
|
||||
- **Lazy Loading Strategies**:
|
||||
- Lazy load API modules that are not immediately required.
|
||||
- Use dynamic imports to load modules on demand.
|
||||
|
||||
### 4. Security Best Practices:
|
||||
|
||||
- **Common Vulnerabilities and How to Prevent Them**:
|
||||
- **Cross-Site Scripting (XSS)**: Sanitize user input to prevent XSS attacks.
|
||||
- **Cross-Site Request Forgery (CSRF)**: Implement CSRF protection mechanisms.
|
||||
- **Man-in-the-Middle (MITM) Attacks**: Use HTTPS to encrypt communication between the client and the server.
|
||||
|
||||
- **Input Validation**:
|
||||
- Validate user input on both the client and server sides.
|
||||
- Use appropriate validation libraries to prevent injection attacks.
|
||||
|
||||
- **Authentication and Authorization Patterns**:
|
||||
- Use a secure authentication protocol (e.g., OAuth 2.0, OpenID Connect).
|
||||
- Implement role-based access control (RBAC) to restrict access to sensitive data.
|
||||
|
||||
- **Data Protection Strategies**:
|
||||
- Encrypt sensitive data at rest and in transit.
|
||||
- Use appropriate data masking techniques to protect sensitive information.
|
||||
|
||||
- **Secure API Communication**:
|
||||
- Use HTTPS for all API communication.
|
||||
- Implement rate limiting to prevent abuse.
|
||||
- Monitor API traffic for suspicious activity.
|
||||
|
||||
### 5. Testing Approaches:
|
||||
|
||||
- **Unit Testing Strategies**:
|
||||
- Mock Axios requests using libraries like `axios-mock-adapter` or `nock`.
|
||||
- Test individual API functions in isolation.
|
||||
- Verify that requests are made with the correct parameters and headers.
|
||||
|
||||
- **Integration Testing**:
|
||||
- Test the interaction between API modules and components.
|
||||
- Verify that data is fetched and displayed correctly.
|
||||
- Use a testing framework like Jest or Mocha.
|
||||
|
||||
- **End-to-End Testing**:
|
||||
- Test the entire application workflow from the user's perspective.
|
||||
- Use a testing framework like Cypress or Selenium.
|
||||
|
||||
- **Test Organization**:
|
||||
- Organize tests by module or feature.
|
||||
- Use descriptive names for test cases.
|
||||
- Follow a consistent testing style.
|
||||
|
||||
- **Mocking and Stubbing**:
|
||||
- Use mocking to isolate components from external dependencies.
|
||||
- Use stubbing to replace API responses with predefined data.
|
||||
|
||||
### 6. Common Pitfalls and Gotchas:
|
||||
|
||||
- **Frequent Mistakes Developers Make**:
|
||||
- Forgetting to handle errors.
|
||||
- Using incorrect HTTP methods.
|
||||
- Hardcoding URLs.
|
||||
- Not setting appropriate headers.
|
||||
|
||||
- **Edge Cases to Be Aware Of**:
|
||||
- Network errors.
|
||||
- Server downtime.
|
||||
- Rate limiting.
|
||||
- API versioning.
|
||||
|
||||
- **Version-Specific Issues**:
|
||||
- Be aware of breaking changes between Axios versions.
|
||||
- Consult the Axios documentation for specific version information.
|
||||
|
||||
- **Compatibility Concerns**:
|
||||
- Ensure that Axios is compatible with the target browsers and environments.
|
||||
- Use polyfills if necessary.
|
||||
|
||||
- **Debugging Strategies**:
|
||||
- Use the browser's developer tools to inspect network requests.
|
||||
- Log Axios requests and responses to the console.
|
||||
- Use a debugging tool like VS Code's debugger.
|
||||
|
||||
### 7. Tooling and Environment:
|
||||
|
||||
- **Recommended Development Tools**:
|
||||
- VS Code with the ESLint and Prettier extensions.
|
||||
- Axios DevTools for Chrome and Firefox.
|
||||
- Postman or Insomnia for testing API endpoints.
|
||||
|
||||
- **Build Configuration**:
|
||||
- Use a build tool like Webpack or Parcel to bundle the application.
|
||||
- Configure the build tool to optimize the bundle size.
|
||||
|
||||
- **Linting and Formatting**:
|
||||
- Use ESLint with a consistent set of rules to enforce code quality.
|
||||
- Use Prettier to format the code automatically.
|
||||
|
||||
- **Deployment Best Practices**:
|
||||
- Deploy the application to a secure hosting environment.
|
||||
- Configure HTTPS for all API communication.
|
||||
- Monitor the application for errors and performance issues.
|
||||
|
||||
- **CI/CD Integration**:
|
||||
- Integrate automated testing and deployment into the CI/CD pipeline.
|
||||
- Use a CI/CD tool like Jenkins, GitLab CI, or CircleCI.
|
||||
@@ -0,0 +1,5 @@
|
||||
---
|
||||
description: This rule provides comprehensive guidelines for using the Guzzle HTTP client in PHP projects, covering code organization, common patterns, performance, security, testing, and tooling.
|
||||
globs: **/*.php
|
||||
---
|
||||
By following these best practices, you can ensure that your Guzzle-based code is efficient, maintainable, secure, and reliable.
|
||||
@@ -0,0 +1,319 @@
|
||||
---
|
||||
description: This rule provides comprehensive best practices for htmx development, covering code organization, security, performance, testing, and common pitfalls. It aims to guide developers in building robust, maintainable, and secure htmx applications.
|
||||
globs: **/*.html
|
||||
---
|
||||
# htmx Best Practices and Coding Standards
|
||||
|
||||
This document outlines the recommended best practices and coding standards for developing htmx applications. Adhering to these guidelines will help ensure code quality, maintainability, security, and performance.
|
||||
|
||||
## 1. Code Organization and Structure
|
||||
|
||||
### 1.1 Directory Structure Best Practices
|
||||
|
||||
While htmx doesn't enforce a specific directory structure, a well-organized project is crucial for maintainability. Consider the following structure as a starting point:
|
||||
|
||||
|
||||
project-root/
|
||||
├── assets/ # Static assets (CSS, JavaScript, images, fonts)
|
||||
│ ├── css/
|
||||
│ ├── js/
|
||||
│ ├── img/
|
||||
│ └── fonts/
|
||||
├── components/ # Reusable HTML snippets/components
|
||||
│ ├── button.html
|
||||
│ ├── form.html
|
||||
│ └── ...
|
||||
├── layouts/ # Page layouts (e.g., base.html, default.html)
|
||||
│ ├── base.html
|
||||
│ └── ...
|
||||
├── pages/ # Individual pages (e.g., index.html, about.html)
|
||||
│ ├── index.html
|
||||
│ └── ...
|
||||
├── scripts/ # Server-side scripts (Python, Node.js, etc.)
|
||||
│ ├── app.py # Example using Flask
|
||||
│ └── ...
|
||||
├── templates/ # Server-side templates (e.g., Jinja2, Django Templates)
|
||||
│ ├── ...
|
||||
├── .env # Environment variables
|
||||
├── requirements.txt # Python dependencies (if applicable)
|
||||
└── package.json # Node.js dependencies (if applicable)
|
||||
|
||||
|
||||
* **`assets/`**: Contains all static assets like CSS, JavaScript (including htmx extensions), images, and fonts. Organize further into subdirectories for each asset type.
|
||||
* **`components/`**: Stores reusable HTML snippets. These components can be included in various pages or other components to avoid code duplication.
|
||||
* **`layouts/`**: Defines the overall structure of pages. Common elements like headers, footers, and navigation are placed here, allowing pages to inherit a consistent look and feel.
|
||||
* **`pages/`**: Contains the HTML files for individual pages of your application. These pages usually include content and may use components and layouts.
|
||||
* **`scripts/`**: Holds server-side scripts responsible for handling requests, processing data, and rendering HTML responses. These scripts interact with htmx via the HTTP protocol.
|
||||
* **`templates/`**: Used in conjunction with server-side scripting, these are templates processed by the backend to generate HTML dynamically. (Only relevant if you are using a template engine on the backend).
|
||||
|
||||
### 1.2 File Naming Conventions
|
||||
|
||||
* **HTML files:** Use descriptive names in lowercase with hyphens (e.g., `product-details.html`, `user-profile.html`).
|
||||
* **CSS files:** Similar to HTML, use lowercase with hyphens (e.g., `main.css`, `style.css`, `components.css`).
|
||||
* **JavaScript files:** Use camelCase for file names (e.g., `utils.js`, `htmxConfig.js`).
|
||||
* **Component files:** Reflect the component's purpose (e.g., `product-card.html`, `search-form.html`).
|
||||
* **Image files:** Use descriptive names related to the image content (e.g., `product-image-1.jpg`, `user-avatar.png`).
|
||||
|
||||
### 1.3 Module Organization
|
||||
|
||||
For larger htmx projects, consider modularizing your JavaScript code. This promotes code reuse and maintainability. CommonJS or ES modules can be used, depending on your build setup.
|
||||
|
||||
javascript
|
||||
// utils.js
|
||||
export function formatDate(date) {
|
||||
// ...
|
||||
}
|
||||
|
||||
export function truncateText(text, limit) {
|
||||
// ...
|
||||
}
|
||||
|
||||
// main.js
|
||||
import { formatDate, truncateText } from './utils.js';
|
||||
|
||||
// ...
|
||||
|
||||
|
||||
### 1.4 Component Architecture
|
||||
|
||||
Break down your user interface into reusable components. This makes your code easier to understand, test, and maintain. For example, a product card, a search form, or a navigation menu can be created as separate components.
|
||||
|
||||
html
|
||||
<!-- product-card.html -->
|
||||
<div class="product-card">
|
||||
<h3>{{ product.name }}</h3>
|
||||
<img src="{{ product.image }}" alt="{{ product.name }}">
|
||||
<p>{{ product.description }}</p>
|
||||
<button hx-post="/add-to-cart/{{ product.id }}">Add to Cart</button>
|
||||
</div>
|
||||
|
||||
|
||||
### 1.5 Code Splitting Strategies
|
||||
|
||||
In htmx, code splitting can refer to different aspects. While htmx itself doesn't require complex JavaScript bundles, consider these:
|
||||
|
||||
* **HTML Components:** Split large pages into smaller, more manageable components. Load these components on demand using htmx requests to improve initial page load time.
|
||||
* **CSS Files:** Separate your CSS into logical modules (e.g., base styles, component styles, page-specific styles) to avoid loading unnecessary styles on every page.
|
||||
* **htmx Extensions:** Only include the htmx extensions that you are actively using. Do not include all extensions if only a few are needed.
|
||||
|
||||
## 2. Common Patterns and Anti-patterns
|
||||
|
||||
### 2.1 Design Patterns Specific to htmx
|
||||
|
||||
* **Progressive Enhancement:** Design your application to work without JavaScript first, then enhance it with htmx. This ensures accessibility and a baseline level of functionality for all users.
|
||||
* **Hypermedia as the Engine of Application State (HATEOAS):** The core philosophy of htmx. The server should provide all the necessary links and forms for the client to interact with the application. The client simply follows these links and submits the forms; it doesn't need to know the specific URLs or request methods.
|
||||
* **Server-Side Rendering (SSR):** Focus on rendering HTML on the server. This improves initial page load time, SEO, and accessibility. htmx enhances this by enabling dynamic updates without full page reloads.
|
||||
* **Component-Based UI:** Design your UI as a collection of reusable components. Each component manages its own state and behavior, making the application easier to understand and maintain.
|
||||
|
||||
### 2.2 Recommended Approaches for Common Tasks
|
||||
|
||||
* **Form Handling:** Use htmx to submit forms and update the UI based on the server's response. Validate user input on both the client and server sides.
|
||||
* **Pagination:** Implement pagination using htmx to load content in chunks. The server provides links to the next and previous pages, and htmx handles the loading and rendering of the new content.
|
||||
* **Real-Time Updates:** Use WebSockets or Server-Sent Events (SSE) with htmx to display real-time data. The server pushes updates to the client, and htmx updates the UI accordingly.
|
||||
* **Dynamic Search:** Implement live search functionality by sending AJAX requests to the server as the user types. Display the search results in real-time using htmx.
|
||||
* **Modal Dialogs:** Use htmx to load the content of modal dialogs on demand. This avoids loading unnecessary content on initial page load.
|
||||
|
||||
### 2.3 Anti-patterns and Code Smells to Avoid
|
||||
|
||||
* **Over-reliance on JavaScript:** htmx aims to reduce the amount of JavaScript required for web development. Avoid using JavaScript for tasks that can be easily accomplished with htmx attributes.
|
||||
* **Complex Client-Side Logic:** Keep your client-side logic as simple as possible. Move complex logic to the server-side, where it can be more easily tested and maintained.
|
||||
* **Mixing htmx with other Front-end frameworks (React, Angular, Vue):** While technically possible, this defeats the purpose of using htmx. Using htmx with other front-end frameworks will likely increase complexity.
|
||||
* **Ignoring Security Best Practices:** htmx does not automatically protect against security vulnerabilities. Always follow security best practices, such as input validation and output escaping, to prevent XSS attacks.
|
||||
* **Creating API Endpoints that return JSON to only convert it to HTML:** htmx shines when your endpoints return HTML. Avoid the extra steps needed for JSON parsing on the client side.
|
||||
|
||||
### 2.4 State Management Best Practices
|
||||
|
||||
htmx promotes a server-centric approach to state management. The server maintains the application's state, and the client simply displays it. This simplifies client-side code and reduces the risk of inconsistencies between the client and server.
|
||||
|
||||
* **Server-Side Sessions:** Store user-specific data in server-side sessions. This ensures that sensitive data is not exposed to the client.
|
||||
* **Hidden Input Fields:** Use hidden input fields to store data that needs to be persisted across requests. This is useful for maintaining state in forms.
|
||||
* **Cookies:** Use cookies to store small amounts of data on the client-side. Be mindful of cookie size limits and security implications.
|
||||
* **URL Parameters:** Use URL parameters to represent state that can be shared or bookmarked. This is useful for implementing features like filtering and sorting.
|
||||
* **`hx-vals`:** Use `hx-vals` for temporary client-side state that is not critical and doesn't need to be persisted on the server. This is suitable for things like the current step in a multi-step form or the visibility state of a component.
|
||||
|
||||
### 2.5 Error Handling Patterns
|
||||
|
||||
* **HTTP Status Codes:** Use appropriate HTTP status codes to indicate the success or failure of a request. For example, use `200 OK` for successful requests, `400 Bad Request` for invalid input, and `500 Internal Server Error` for server-side errors.
|
||||
* **htmx Error Handling:** htmx provides the `htmx:responseError` event for handling errors. Use this event to display error messages to the user or take other appropriate actions.
|
||||
* **Server-Side Error Pages:** Configure your server to display custom error pages for different HTTP status codes. This provides a user-friendly experience even when errors occur.
|
||||
* **Client-Side Error Messages:** Display informative error messages to the user when a request fails. Avoid displaying technical details that could expose sensitive information.
|
||||
* **Error Logging:** Log errors on the server-side to help diagnose and fix problems. Include relevant information such as the request URL, user ID, and error message.
|
||||
* **Graceful Degradation:** Even when errors occur, ensure that your application degrades gracefully. Provide alternative functionality or a clear explanation of the problem.
|
||||
|
||||
## 3. Performance Considerations
|
||||
|
||||
### 3.1 Optimization Techniques
|
||||
|
||||
* **Minimize DOM Updates:** htmx is efficient at updating the DOM, but excessive updates can still impact performance. Use the `hx-swap` attribute to control how content is swapped into the DOM and minimize unnecessary changes.
|
||||
* **Optimize Server-Side Rendering:** Ensure that your server-side rendering is as efficient as possible. Use caching, compression, and other optimization techniques to reduce the time it takes to generate HTML.
|
||||
* **Compress Static Assets:** Compress your CSS, JavaScript, and image files to reduce their size and improve loading times. Use tools like Gzip or Brotli for compression.
|
||||
* **Use a CDN:** Serve your static assets from a Content Delivery Network (CDN) to improve loading times for users around the world.
|
||||
* **Lazy Load Images:** Load images only when they are visible in the viewport. This reduces initial page load time and improves performance.
|
||||
* **Throttle and Debounce Events:** When using events like `keyup` or `mousemove` with `hx-trigger`, use the `throttle` and `debounce` modifiers to limit the number of requests sent to the server.
|
||||
|
||||
### 3.2 Memory Management
|
||||
|
||||
* **Avoid Memory Leaks:** Be careful to avoid memory leaks in your JavaScript code. Remove event listeners when they are no longer needed and avoid creating circular references.
|
||||
* **Minimize DOM Elements:** Reduce the number of DOM elements on your page as much as possible. Complex layouts with many nested elements can impact performance.
|
||||
* **Use Event Delegation:** Use event delegation to attach event listeners to a parent element instead of attaching them to individual child elements. This reduces the number of event listeners and improves performance.
|
||||
|
||||
### 3.3 Rendering Optimization
|
||||
|
||||
* **Use Efficient CSS Selectors:** Use efficient CSS selectors to minimize the time it takes to apply styles to your elements. Avoid complex selectors that traverse the DOM unnecessarily.
|
||||
* **Avoid Reflows and Repaints:** Avoid triggering reflows and repaints in your JavaScript code. These operations can be expensive and impact performance. Read properties before making changes to the DOM, and batch your DOM updates.
|
||||
* **Use Hardware Acceleration:** Take advantage of hardware acceleration to improve rendering performance. Use CSS properties like `transform` and `opacity` to trigger hardware acceleration.
|
||||
|
||||
### 3.4 Bundle Size Optimization
|
||||
|
||||
* **Minimize Dependencies:** Use only the dependencies that you absolutely need. Avoid including large libraries that you only use for a small number of features.
|
||||
* **Tree Shaking:** Use a bundler that supports tree shaking to remove unused code from your JavaScript bundles.
|
||||
* **Code Splitting:** Split your code into smaller chunks that can be loaded on demand. This reduces the initial download size and improves performance.
|
||||
|
||||
### 3.5 Lazy Loading Strategies
|
||||
|
||||
* **Lazy Load Images:** Load images only when they are visible in the viewport. This reduces initial page load time and improves performance. Use the `loading="lazy"` attribute on `<img>` elements.
|
||||
* **Lazy Load Components:** Load components only when they are needed. Use htmx to load the component's HTML when it is first requested.
|
||||
* **Intersection Observer API:** Use the Intersection Observer API to detect when an element enters the viewport. This can be used to trigger the lazy loading of images or components.
|
||||
|
||||
## 4. Security Best Practices
|
||||
|
||||
### 4.1 Common Vulnerabilities and How to Prevent Them
|
||||
|
||||
* **Cross-Site Scripting (XSS):** Prevent XSS attacks by escaping user input and avoiding the use of `innerHTML`. Use template engines that automatically escape output.
|
||||
* **Cross-Site Request Forgery (CSRF):** Protect against CSRF attacks by using anti-CSRF tokens in your forms. Most server-side frameworks provide built-in CSRF protection.
|
||||
* **SQL Injection:** Prevent SQL injection attacks by using parameterized queries or ORMs. Never construct SQL queries by concatenating user input.
|
||||
* **Authentication and Authorization:** Implement proper authentication and authorization mechanisms to protect your application from unauthorized access.
|
||||
* **Sensitive Data Exposure:** Avoid exposing sensitive data in URLs or client-side code. Store sensitive data securely on the server-side.
|
||||
|
||||
### 4.2 Input Validation
|
||||
|
||||
* **Client-Side Validation:** Use client-side validation to provide immediate feedback to the user and prevent invalid data from being submitted to the server. However, never rely solely on client-side validation.
|
||||
* **Server-Side Validation:** Always validate user input on the server-side. This is the only way to ensure that your application is protected from invalid or malicious data.
|
||||
* **Sanitize User Input:** Sanitize user input to remove or escape potentially harmful characters. This can help prevent XSS and other attacks.
|
||||
|
||||
### 4.3 Authentication and Authorization Patterns
|
||||
|
||||
* **Cookie-Based Authentication:** Use cookies to store authentication tokens. Set the `Secure`, `HttpOnly`, and `SameSite` attributes to protect your cookies from unauthorized access.
|
||||
* **Session Management:** Use server-side sessions to store user-specific data. This prevents sensitive data from being exposed to the client.
|
||||
* **Role-Based Access Control (RBAC):** Implement RBAC to control access to different parts of your application based on user roles. This ensures that users can only access the resources that they are authorized to access.
|
||||
|
||||
### 4.4 Data Protection Strategies
|
||||
|
||||
* **Encryption:** Encrypt sensitive data both in transit and at rest. Use HTTPS to encrypt data in transit, and use strong encryption algorithms to encrypt data at rest.
|
||||
* **Hashing:** Use hashing to store passwords and other sensitive data. Never store passwords in plaintext.
|
||||
* **Data Masking:** Mask sensitive data in your application's UI to prevent it from being exposed to unauthorized users. For example, you can mask credit card numbers or social security numbers.
|
||||
|
||||
### 4.5 Secure API Communication
|
||||
|
||||
* **HTTPS:** Always use HTTPS to encrypt communication between the client and server.
|
||||
* **API Authentication:** Require API clients to authenticate themselves before accessing your API. Use API keys, OAuth, or other authentication mechanisms.
|
||||
* **Rate Limiting:** Implement rate limiting to prevent API abuse. This limits the number of requests that a client can make in a given period of time.
|
||||
* **Input Validation:** Validate all input to your API to prevent injection attacks and other security vulnerabilities.
|
||||
* **Output Sanitization:** Sanitize all output from your API to prevent XSS attacks.
|
||||
* **CORS (Cross-Origin Resource Sharing):** Configure CORS carefully to allow only trusted domains to access your API.
|
||||
|
||||
### 4.6 The Golden Rules of htmx Security (reiterated):
|
||||
|
||||
* **Only call routes you control**: Use relative URLs to avoid executing untrusted code.
|
||||
* **Always use an auto-escaping template engine**: Prevent XSS attacks by ensuring dynamic content is escaped.
|
||||
* **Only serve user-generated content inside HTML tags**: Avoid inserting user content in dangerous contexts like script or style tags.
|
||||
* **Secure your cookies**: Use attributes like Secure, HttpOnly, and SameSite=Lax for authentication cookies.
|
||||
|
||||
## 5. Testing Approaches
|
||||
|
||||
### 5.1 Unit Testing Strategies
|
||||
|
||||
* **Test Server-Side Logic:** Write unit tests for your server-side logic to ensure that it is working correctly. Use a testing framework like pytest (Python), Jest (Node.js), or JUnit (Java).
|
||||
* **Test htmx Endpoints:** Write tests for your htmx endpoints. This could involve making requests to your endpoints and checking the HTML responses.
|
||||
* **Mock External Dependencies:** Mock external dependencies, such as databases or APIs, to isolate your code and make your tests more reliable.
|
||||
|
||||
### 5.2 Integration Testing
|
||||
|
||||
* **Test Interactions Between Components:** Write integration tests to ensure that your components are working together correctly. This includes testing the interactions between htmx attributes and JavaScript code.
|
||||
* **Test Data Flow:** Test the flow of data through your application to ensure that data is being processed and displayed correctly.
|
||||
|
||||
### 5.3 End-to-End Testing
|
||||
|
||||
* **Simulate User Interactions:** Write end-to-end tests to simulate user interactions with your application. This includes testing the entire workflow from start to finish.
|
||||
* **Test UI Rendering:** Test the rendering of your UI to ensure that it is displaying correctly. This includes testing the layout, styles, and content of your pages.
|
||||
|
||||
### 5.4 Test Organization
|
||||
|
||||
* **Organize Tests by Feature:** Organize your tests by feature to make it easier to find and run tests for specific parts of your application.
|
||||
* **Use a Consistent Naming Convention:** Use a consistent naming convention for your tests to make them easier to understand and maintain.
|
||||
* **Keep Tests Independent:** Keep your tests independent of each other to avoid cascading failures.
|
||||
|
||||
### 5.5 Mocking and Stubbing
|
||||
|
||||
* **Use Mocking to Isolate Code:** Use mocking to isolate your code and make your tests more reliable. This involves replacing external dependencies with mock objects that simulate their behavior.
|
||||
* **Use Stubbing to Control Behavior:** Use stubbing to control the behavior of your mock objects. This allows you to test different scenarios and edge cases.
|
||||
|
||||
## 6. Common Pitfalls and Gotchas
|
||||
|
||||
### 6.1 Frequent Mistakes Developers Make
|
||||
|
||||
* **Incorrect `hx-target` and `hx-swap` Usage:** Pay close attention to the `hx-target` and `hx-swap` attributes. Incorrect usage can lead to unexpected results and broken UI.
|
||||
* **Forgetting Server-Side Validation:** Always validate user input on the server-side. Client-side validation is not sufficient for security.
|
||||
* **Over-complicating Client-Side Logic:** htmx is designed to simplify client-side code. Avoid adding unnecessary complexity.
|
||||
* **Ignoring Accessibility:** Make sure your htmx application is accessible to all users. Use semantic HTML, provide alternative text for images, and ensure that your application is keyboard-navigable.
|
||||
* **Not handling edge cases and error conditions**: Ensure you have covered the most common error conditions, such as server errors, network issues, and no results.
|
||||
|
||||
### 6.2 Edge Cases to Be Aware Of
|
||||
|
||||
* **Handling Empty Responses:** Consider how your application should behave when the server returns an empty response. Should the target element be cleared, or should a default message be displayed?
|
||||
* **Handling Concurrent Requests:** Be aware of the potential for concurrent requests. Use the `hx-sync` attribute to manage synchronization between requests.
|
||||
* **Handling Browser History:** htmx does not automatically manage browser history. If you need to support browser history, you will need to use JavaScript or a dedicated htmx extension.
|
||||
* **Unexpected interactions with browser extensions**: Some browser extensions, especially those that modify HTTP headers, can interfere with htmx's behavior. Test your application with common extensions enabled to identify and address any conflicts.
|
||||
|
||||
### 6.3 Version-Specific Issues
|
||||
|
||||
* **Refer to the Official Documentation:** Always refer to the official htmx documentation for the latest information and best practices.
|
||||
* **Check Release Notes:** Review the release notes for each new version of htmx to identify any breaking changes or known issues.
|
||||
|
||||
### 6.4 Compatibility Concerns
|
||||
|
||||
* **Browser Compatibility:** htmx is compatible with modern browsers. However, older browsers may require polyfills.
|
||||
* **Server-Side Framework Compatibility:** htmx can be used with any server-side framework that can generate HTML. However, some frameworks may require specific configuration.
|
||||
|
||||
### 6.5 Debugging Strategies
|
||||
|
||||
* **Use Browser Developer Tools:** Use your browser's developer tools to inspect network requests, examine the DOM, and debug JavaScript code.
|
||||
* **htmx Events:** Listen for htmx events, such as `htmx:beforeRequest`, `htmx:afterRequest`, and `htmx:responseError`, to gain insight into what is happening in your application.
|
||||
* **Server-Side Logging:** Add logging to your server-side code to help diagnose problems.
|
||||
* **Simplify the Problem:** Break down complex htmx interactions into smaller, more manageable steps to isolate the source of the problem.
|
||||
* **Inspect HTTP Headers:** Pay attention to the HTTP headers in both the request and response. Check the `Content-Type`, `HX-Request`, and other relevant headers.
|
||||
|
||||
## 7. Tooling and Environment
|
||||
|
||||
### 7.1 Recommended Development Tools
|
||||
|
||||
* **Text Editor or IDE:** Use a text editor or IDE with support for HTML, CSS, and JavaScript. Popular options include VS Code, Sublime Text, and Atom.
|
||||
* **Browser Developer Tools:** Use your browser's developer tools to inspect network requests, examine the DOM, and debug JavaScript code.
|
||||
* **htmx Extension for Chrome:** Install the htmx extension for Chrome to enable features like attribute highlighting and event inspection.
|
||||
* **Server-Side Development Tools:** Use the development tools appropriate for your chosen server-side framework (e.g., Python debugger, Node.js inspector).
|
||||
|
||||
### 7.2 Build Configuration
|
||||
|
||||
* **Use a Task Runner:** Use a task runner like Gulp or Grunt to automate common development tasks, such as minifying CSS and JavaScript, optimizing images, and running tests.
|
||||
* **Use a Module Bundler:** Use a module bundler like Webpack or Parcel to bundle your JavaScript modules into a single file.
|
||||
* **Configure Code Linting and Formatting:** Integrate linters (like ESLint, stylelint) and formatters (like Prettier) to automatically enforce consistent coding styles and catch common errors.
|
||||
|
||||
### 7.3 Linting and Formatting
|
||||
|
||||
* **Use a Code Linter:** Use a code linter to automatically detect errors and enforce coding style guidelines. Popular linters include ESLint (JavaScript) and stylelint (CSS).
|
||||
* **Use a Code Formatter:** Use a code formatter to automatically format your code according to a consistent style. Popular formatters include Prettier and js-beautify.
|
||||
|
||||
### 7.4 Deployment Best Practices
|
||||
|
||||
* **Use a Version Control System:** Use a version control system like Git to track changes to your code. This makes it easier to collaborate with others and revert to previous versions if necessary.
|
||||
* **Automate Deployment:** Automate your deployment process using a tool like Jenkins, Travis CI, or CircleCI. This makes it easier to deploy your application to production quickly and reliably.
|
||||
* **Use a Continuous Integration/Continuous Deployment (CI/CD) Pipeline:** Implement a CI/CD pipeline to automatically build, test, and deploy your application whenever changes are made to your codebase.
|
||||
* **Monitor Your Application:** Monitor your application in production to detect and resolve problems quickly.
|
||||
|
||||
### 7.5 CI/CD Integration
|
||||
|
||||
* **Set Up a CI/CD Pipeline:** Set up a CI/CD pipeline to automatically build, test, and deploy your application. This makes it easier to release new features and bug fixes quickly and reliably.
|
||||
* **Run Tests Automatically:** Configure your CI/CD pipeline to run your tests automatically whenever changes are made to your codebase. This helps to ensure that your code is working correctly before it is deployed to production.
|
||||
* **Automate Deployment:** Automate your deployment process using a tool like Jenkins, Travis CI, or CircleCI. This makes it easier to deploy your application to production quickly and reliably.
|
||||
|
||||
By adhering to these best practices and coding standards, you can build htmx applications that are robust, maintainable, secure, and performant. Remember to stay up-to-date with the latest htmx documentation and community resources to ensure that you are using the most effective techniques.
|
||||
@@ -0,0 +1,353 @@
|
||||
---
|
||||
description: This rule provides comprehensive guidance on tRPC best practices, covering code organization, performance, security, testing, and common pitfalls to ensure robust and maintainable tRPC applications.
|
||||
globs: **/*.{ts,tsx}
|
||||
---
|
||||
# tRPC Best Practices: A Comprehensive Guide
|
||||
|
||||
This document outlines best practices for developing robust, maintainable, and efficient applications using tRPC (TypeScript Remote Procedure Call). It covers various aspects, from code organization to security considerations, providing actionable guidance for developers.
|
||||
|
||||
## 1. Code Organization and Structure
|
||||
|
||||
### 1.1 Directory Structure Best Practices
|
||||
|
||||
* **Feature-Based Organization:** Organize your code around features or modules, rather than technical layers (e.g., `components`, `utils`, `services`). This promotes modularity and maintainability. For example:
|
||||
|
||||
|
||||
src/
|
||||
├── features/
|
||||
│ ├── user/
|
||||
│ │ ├── components/
|
||||
│ │ │ ├── UserProfile.tsx
|
||||
│ │ │ └── UserSettings.tsx
|
||||
│ │ ├── api/
|
||||
│ │ │ ├── userRouter.ts // tRPC router for user-related procedures
|
||||
│ │ │ └── userSchema.ts // Zod schemas for input validation
|
||||
│ │ ├── hooks/
|
||||
│ │ │ └── useUser.ts // Custom hooks for data fetching and state management
|
||||
│ │ └── types/
|
||||
│ │ │ └── user.ts // TypeScript types related to users
|
||||
│ ├── product/
|
||||
│ │ └── ...
|
||||
├── utils/
|
||||
│ ├── api.ts // tRPC client initialization
|
||||
│ └── db.ts // Database connection/abstraction
|
||||
├── app/
|
||||
│ ├── api/
|
||||
│ │ └── root.ts // Root tRPC router combining all feature routers
|
||||
│ └── context.ts // tRPC context creation
|
||||
└── index.ts // Server entry point
|
||||
|
||||
|
||||
* **Separation of Concerns:** Separate concerns into different directories and modules. For instance, keep your tRPC router definitions separate from your business logic and data access layers.
|
||||
* **Grouping Similar Functionality:** Keep related files together within a feature directory. This makes it easier to understand and maintain the code.
|
||||
|
||||
### 1.2 File Naming Conventions
|
||||
|
||||
* **Descriptive Names:** Use descriptive names for files and directories that clearly indicate their purpose.
|
||||
* **Consistent Case:** Maintain a consistent casing convention (e.g., camelCase for variables, PascalCase for components). Use `kebab-case` for file names e.g. `user-profile.tsx` or `user.router.ts`
|
||||
* **Suffixes:** Use suffixes to indicate the type of file (e.g., `.router.ts` for tRPC routers, `.schema.ts` for Zod schemas, `.component.tsx` for React components).
|
||||
|
||||
### 1.3 Module Organization
|
||||
|
||||
* **Small Modules:** Keep modules small and focused. A module should have a single responsibility. Aim for modules that are easy to understand and test.
|
||||
* **Explicit Exports:** Use explicit exports to control what is exposed from a module. This helps to prevent accidental exposure of internal implementation details.
|
||||
* **Circular Dependencies:** Avoid circular dependencies between modules. Circular dependencies can lead to unexpected behavior and make it difficult to reason about the code.
|
||||
|
||||
### 1.4 Component Architecture
|
||||
|
||||
* **Presentational and Container Components:** Separate presentational (dumb) components from container (smart) components. Presentational components focus on rendering UI, while container components handle data fetching and state management. Use the term `view` instead of `component` in the file suffix can make a separation between React components and presentational components, e.g. `user-profile.view.tsx`
|
||||
* **Reusable Components:** Design components to be reusable across different parts of the application. This reduces code duplication and improves maintainability.
|
||||
* **Component Composition:** Favor component composition over inheritance. Composition allows you to create more flexible and reusable components.
|
||||
|
||||
### 1.5 Code Splitting Strategies
|
||||
|
||||
* **Route-Based Splitting:** Split your code based on routes. This allows you to load only the code that is needed for a specific route. This can be easily achieved with React's `lazy` and `Suspense` APIs.
|
||||
* **Component-Based Splitting:** Split your code based on components. This allows you to load only the code that is needed for a specific component.
|
||||
* **Dynamic Imports:** Use dynamic imports to load code on demand. This can be useful for loading large libraries or components that are not needed immediately.
|
||||
|
||||
## 2. Common Patterns and Anti-patterns
|
||||
|
||||
### 2.1 Design Patterns Specific to tRPC
|
||||
|
||||
* **Router Composition:** Compose tRPC routers to create a hierarchical API structure. This allows you to organize your API into logical groups.
|
||||
|
||||
typescript
|
||||
// src/app/api/routers/userRouter.ts
|
||||
import { publicProcedure, router } from "../trpc";
|
||||
import { z } from "zod";
|
||||
|
||||
export const userRouter = router({
|
||||
getById: publicProcedure
|
||||
.input(z.string())
|
||||
.query(async ({ input }) => {
|
||||
// ... fetch user by ID
|
||||
}),
|
||||
create: publicProcedure
|
||||
.input(z.object({ name: z.string() }))
|
||||
.mutation(async ({ input }) => {
|
||||
// ... create a new user
|
||||
}),
|
||||
});
|
||||
|
||||
// src/app/api/root.ts
|
||||
import { userRouter } from "./routers/userRouter";
|
||||
import { productRouter } from "./routers/productRouter";
|
||||
|
||||
export const appRouter = router({
|
||||
user: userRouter,
|
||||
product: productRouter,
|
||||
});
|
||||
|
||||
export type AppRouter = typeof appRouter;
|
||||
|
||||
|
||||
* **Middleware Chaining:** Use middleware to handle cross-cutting concerns such as authentication, authorization, and logging. Middleware can be chained to create a pipeline of operations.
|
||||
|
||||
typescript
|
||||
// src/app/api/trpc.ts
|
||||
import { initTRPC, TRPCError } from "@trpc/server";
|
||||
import { Context } from "./context";
|
||||
|
||||
const t = initTRPC.context<Context>().create();
|
||||
const isAuthed = t.middleware(({ ctx, next }) => {
|
||||
if (!ctx.user) {
|
||||
throw new TRPCError({ code: "UNAUTHORIZED" });
|
||||
}
|
||||
return next({
|
||||
ctx: {
|
||||
user: ctx.user,
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
export const router = t.router;
|
||||
export const publicProcedure = t.procedure;
|
||||
export const protectedProcedure = t.procedure.use(isAuthed);
|
||||
|
||||
|
||||
* **Input Validation with Zod:** Use Zod for input validation to ensure that data received from the client is valid. This helps to prevent errors and security vulnerabilities.
|
||||
|
||||
typescript
|
||||
import { z } from "zod";
|
||||
import { publicProcedure } from "../trpc";
|
||||
|
||||
export const createUserProcedure = publicProcedure
|
||||
.input(z.object({ name: z.string().min(3), email: z.string().email() }))
|
||||
.mutation(async ({ input }) => {
|
||||
// ... create a new user
|
||||
});
|
||||
|
||||
|
||||
### 2.2 Recommended Approaches for Common Tasks
|
||||
|
||||
* **Authentication:** Use tRPC middleware to authenticate users. Verify user credentials and set the user object in the context.
|
||||
* **Authorization:** Use tRPC middleware to authorize users. Check if the user has the required permissions to access a resource.
|
||||
* **Error Handling:** Use tRPC's built-in error handling mechanisms to handle errors gracefully. Throw `TRPCError` exceptions with appropriate error codes and messages.
|
||||
* **Data Fetching:** Use a data fetching library (e.g., Prisma, Drizzle ORM, Supabase) to interact with your database. Abstract data access logic into separate modules or services.
|
||||
|
||||
### 2.3 Anti-patterns and Code Smells to Avoid
|
||||
|
||||
* **Over-fetching:** Avoid fetching more data than you need. Use projections or GraphQL-style queries to fetch only the required fields.
|
||||
* **Under-fetching:** Avoid making multiple API calls to fetch related data. Batch requests or use a data loader pattern to fetch related data in a single call.
|
||||
* **Tight Coupling:** Avoid tight coupling between tRPC routers and your business logic. Abstract business logic into separate modules or services.
|
||||
* **Ignoring Errors:** Never ignore errors. Always handle errors gracefully and provide meaningful feedback to the client.
|
||||
* **Direct Database Access in Routers:** Avoid accessing the database directly within tRPC router procedures. Instead, abstract data access into separate services or repositories.
|
||||
* **Complex Business Logic in Routers:** Keep tRPC router procedures focused on routing and input validation. Move complex business logic to separate functions or modules.
|
||||
|
||||
### 2.4 State Management Best Practices
|
||||
|
||||
* **Centralized State Management:** Use a centralized state management library (e.g., Zustand, Redux, Jotai) to manage application state. This makes it easier to share state between components and to reason about the application's state.
|
||||
* **Immutable State:** Use immutable state to prevent unexpected side effects. This makes it easier to reason about the application's state and to debug issues.
|
||||
* **Controlled Components:** Use controlled components to manage form state. This gives you more control over the form and makes it easier to validate input.
|
||||
* **Server State Management:** Use a library like TanStack Query or SWR to manage server state (data fetched from the API). These libraries provide caching, optimistic updates, and other features that make it easier to manage server state.
|
||||
|
||||
### 2.5 Error Handling Patterns
|
||||
|
||||
* **Centralized Error Handling:** Use a centralized error handling mechanism to handle errors consistently across the application.
|
||||
* **Error Boundaries:** Use error boundaries to prevent errors from crashing the application. Error boundaries can catch errors that occur during rendering and display a fallback UI.
|
||||
* **Logging:** Log errors to a central logging service. This makes it easier to track down and fix issues.
|
||||
* **User-Friendly Error Messages:** Display user-friendly error messages to the user. Avoid displaying technical details or stack traces.
|
||||
* **Retry Mechanism:** Implement a retry mechanism for transient errors. This can improve the resilience of the application.
|
||||
|
||||
## 3. Performance Considerations
|
||||
|
||||
### 3.1 Optimization Techniques
|
||||
|
||||
* **Caching:** Implement caching to reduce the number of API calls. Cache data on the server and the client.
|
||||
* **Compression:** Use compression to reduce the size of API responses. This can improve the performance of the application, especially on slow networks.
|
||||
* **Code Splitting:** Split your code into smaller chunks to reduce the initial load time. Load code on demand as needed.
|
||||
* **Debouncing and Throttling:** Use debouncing and throttling to reduce the number of API calls triggered by user input.
|
||||
* **Efficient Data Structures:** Use efficient data structures to store and process data. Choose the right data structure for the task at hand.
|
||||
|
||||
### 3.2 Memory Management
|
||||
|
||||
* **Avoid Memory Leaks:** Be careful to avoid memory leaks. Memory leaks can cause the application to slow down and eventually crash.
|
||||
* **Garbage Collection:** Understand how garbage collection works in JavaScript. This can help you to avoid memory leaks and to optimize memory usage.
|
||||
* **Use Weak References:** Use weak references to avoid keeping objects in memory longer than necessary.
|
||||
|
||||
### 3.3 Rendering Optimization
|
||||
|
||||
* **Memoization:** Use memoization to avoid re-rendering components unnecessarily. Memoize components that receive the same props multiple times.
|
||||
* **Virtualization:** Use virtualization to render large lists efficiently. Virtualization only renders the items that are visible on the screen.
|
||||
* **Batch Updates:** Batch updates to reduce the number of re-renders. React's `useState` hook batches updates automatically.
|
||||
|
||||
### 3.4 Bundle Size Optimization
|
||||
|
||||
* **Tree Shaking:** Use tree shaking to remove unused code from the bundle. This can significantly reduce the bundle size.
|
||||
* **Code Minification:** Minify your code to reduce the bundle size. Minification removes whitespace and comments from the code.
|
||||
* **Image Optimization:** Optimize images to reduce the bundle size. Use appropriate image formats and compress images.
|
||||
* **Dependency Analysis:** Analyze your dependencies to identify large or unnecessary dependencies. Consider replacing large dependencies with smaller alternatives.
|
||||
|
||||
### 3.5 Lazy Loading Strategies
|
||||
|
||||
* **Lazy Load Images:** Lazy load images to improve the initial load time. Only load images when they are visible on the screen.
|
||||
* **Lazy Load Components:** Lazy load components to improve the initial load time. Only load components when they are needed.
|
||||
* **Lazy Load Modules:** Lazy load modules to improve the initial load time. Only load modules when they are needed.
|
||||
|
||||
## 4. Security Best Practices
|
||||
|
||||
### 4.1 Common Vulnerabilities and How to Prevent Them
|
||||
|
||||
* **Cross-Site Scripting (XSS):** Prevent XSS attacks by escaping user input and using a content security policy (CSP).
|
||||
* **Cross-Site Request Forgery (CSRF):** Prevent CSRF attacks by using CSRF tokens. Most frameworks have built-in support for CSRF protection.
|
||||
* **SQL Injection:** Prevent SQL injection attacks by using parameterized queries or an ORM.
|
||||
* **Authentication and Authorization:** Implement strong authentication and authorization mechanisms to protect sensitive data.
|
||||
* **Rate Limiting:** Implement rate limiting to prevent brute-force attacks.
|
||||
* **Denial-of-Service (DoS):** Implement measures to prevent DoS attacks, such as rate limiting and input validation.
|
||||
|
||||
### 4.2 Input Validation
|
||||
|
||||
* **Validate All Input:** Validate all input from the client, including query parameters, request bodies, and headers.
|
||||
* **Use Strong Types:** Use strong types to define the expected format of input data. This can help to prevent type-related errors and security vulnerabilities. Tools like Zod are invaluable here.
|
||||
* **Sanitize Input:** Sanitize input to remove potentially harmful characters or code. This can help to prevent XSS attacks.
|
||||
* **Whitelist Input:** Whitelist allowed input values. This is more secure than blacklisting disallowed values.
|
||||
|
||||
### 4.3 Authentication and Authorization Patterns
|
||||
|
||||
* **JWT (JSON Web Tokens):** Use JWTs for authentication. JWTs are a standard way to securely transmit information between parties as a JSON object.
|
||||
* **OAuth 2.0:** Use OAuth 2.0 for authorization. OAuth 2.0 is a standard protocol for delegating access to resources.
|
||||
* **Role-Based Access Control (RBAC):** Use RBAC to control access to resources based on user roles. This makes it easier to manage permissions and to enforce security policies.
|
||||
* **Attribute-Based Access Control (ABAC):** Use ABAC to control access to resources based on user attributes. This provides more fine-grained control over access to resources.
|
||||
|
||||
### 4.4 Data Protection Strategies
|
||||
|
||||
* **Encryption:** Encrypt sensitive data at rest and in transit. Use strong encryption algorithms.
|
||||
* **Hashing:** Hash passwords and other sensitive data. Use a strong hashing algorithm with a salt.
|
||||
* **Data Masking:** Mask sensitive data in logs and other outputs. This prevents sensitive data from being exposed accidentally.
|
||||
* **Data Redaction:** Redact sensitive data from API responses. This prevents sensitive data from being exposed to unauthorized users.
|
||||
|
||||
### 4.5 Secure API Communication
|
||||
|
||||
* **HTTPS:** Use HTTPS for all API communication. HTTPS encrypts the communication between the client and the server, protecting it from eavesdropping and tampering.
|
||||
* **CORS (Cross-Origin Resource Sharing):** Configure CORS to restrict access to your API from unauthorized domains. This helps to prevent cross-site scripting attacks.
|
||||
* **Rate Limiting:** Implement rate limiting to prevent brute-force attacks and DoS attacks.
|
||||
* **API Keys:** Use API keys to authenticate API clients. This helps to prevent unauthorized access to your API.
|
||||
|
||||
## 5. Testing Approaches
|
||||
|
||||
### 5.1 Unit Testing Strategies
|
||||
|
||||
* **Test Individual Functions and Modules:** Unit tests should focus on testing individual functions and modules in isolation.
|
||||
* **Mock Dependencies:** Mock dependencies to isolate the code under test. This prevents external dependencies from interfering with the test.
|
||||
* **Test Edge Cases:** Test edge cases to ensure that the code handles unexpected input correctly.
|
||||
* **Test Error Handling:** Test error handling to ensure that the code handles errors gracefully.
|
||||
* **Use Test-Driven Development (TDD):** Consider using TDD to write tests before writing code. This can help to improve the design of the code and to ensure that it is testable.
|
||||
|
||||
### 5.2 Integration Testing
|
||||
|
||||
* **Test Interactions Between Modules:** Integration tests should focus on testing the interactions between modules. This ensures that the modules work together correctly.
|
||||
* **Use Real Dependencies:** Use real dependencies in integration tests. This provides more realistic testing conditions.
|
||||
* **Test Data Flow:** Test the data flow between modules to ensure that data is passed correctly.
|
||||
|
||||
### 5.3 End-to-End Testing
|
||||
|
||||
* **Test the Entire Application:** End-to-end tests should focus on testing the entire application, from the user interface to the backend API.
|
||||
* **Use a Test Automation Framework:** Use a test automation framework (e.g., Cypress, Playwright) to automate end-to-end tests. This makes it easier to run the tests and to verify that the application is working correctly.
|
||||
* **Test User Flows:** Test common user flows to ensure that users can complete important tasks.
|
||||
|
||||
### 5.4 Test Organization
|
||||
|
||||
* **Organize Tests by Feature:** Organize tests by feature. This makes it easier to find and run tests for a specific feature.
|
||||
* **Keep Tests Separate from Code:** Keep tests separate from the code. This prevents tests from being included in the production bundle.
|
||||
* **Use a Consistent Naming Convention:** Use a consistent naming convention for tests. This makes it easier to identify and understand the tests.
|
||||
|
||||
### 5.5 Mocking and Stubbing
|
||||
|
||||
* **Use Mocking Frameworks:** Use mocking frameworks (e.g., Jest, Sinon) to create mocks and stubs. This makes it easier to isolate the code under test.
|
||||
* **Mock External Dependencies:** Mock external dependencies to prevent them from interfering with the test.
|
||||
* **Stub API Responses:** Stub API responses to control the data that is returned by the API.
|
||||
|
||||
## 6. Common Pitfalls and Gotchas
|
||||
|
||||
### 6.1 Frequent Mistakes Developers Make
|
||||
|
||||
* **Not Validating Input:** Failing to validate input is a common mistake that can lead to errors and security vulnerabilities.
|
||||
* **Ignoring Errors:** Ignoring errors can make it difficult to debug issues and can lead to unexpected behavior.
|
||||
* **Over-Complicating Code:** Over-complicating code can make it difficult to understand and maintain.
|
||||
* **Not Writing Tests:** Not writing tests can lead to bugs and can make it difficult to refactor the code.
|
||||
* **Incorrect Context Usage:** Misunderstanding how the tRPC context works, especially when dealing with middleware and authentication.
|
||||
|
||||
### 6.2 Edge Cases to Be Aware Of
|
||||
|
||||
* **Empty Input:** Handle empty input gracefully. Provide default values or display an error message.
|
||||
* **Invalid Input:** Handle invalid input gracefully. Display an error message to the user.
|
||||
* **Network Errors:** Handle network errors gracefully. Display an error message to the user and provide a way to retry the request.
|
||||
* **Server Errors:** Handle server errors gracefully. Display an error message to the user and log the error on the server.
|
||||
* **Concurrency Issues:** Be aware of concurrency issues when dealing with shared resources. Use locks or other synchronization mechanisms to prevent data corruption.
|
||||
|
||||
### 6.3 Version-Specific Issues
|
||||
|
||||
* **Breaking Changes:** Be aware of breaking changes when upgrading tRPC. Review the release notes carefully and update your code accordingly.
|
||||
* **Deprecated Features:** Be aware of deprecated features. Replace deprecated features with the recommended alternatives.
|
||||
* **Compatibility Issues:** Be aware of compatibility issues with other libraries. Test your code thoroughly after upgrading tRPC or other libraries.
|
||||
|
||||
### 6.4 Compatibility Concerns
|
||||
|
||||
* **Browser Compatibility:** Ensure that your code is compatible with the browsers that you support.
|
||||
* **Node.js Version Compatibility:** Ensure that your code is compatible with the Node.js versions that you support.
|
||||
* **TypeScript Version Compatibility:** Ensure that your code is compatible with the TypeScript version that you are using.
|
||||
|
||||
### 6.5 Debugging Strategies
|
||||
|
||||
* **Use Debugging Tools:** Use debugging tools (e.g., Chrome DevTools, VS Code debugger) to step through your code and inspect variables.
|
||||
* **Add Logging Statements:** Add logging statements to your code to track the flow of execution and to identify errors.
|
||||
* **Use a Debugger:** Use a debugger to pause the execution of your code and to inspect the state of the application.
|
||||
* **Reproduce the Issue:** Try to reproduce the issue in a controlled environment. This makes it easier to identify the cause of the issue.
|
||||
|
||||
## 7. Tooling and Environment
|
||||
|
||||
### 7.1 Recommended Development Tools
|
||||
|
||||
* **VS Code:** Use VS Code as your IDE. VS Code provides excellent support for TypeScript and JavaScript development.
|
||||
* **ESLint:** Use ESLint to enforce code style and to prevent errors.
|
||||
* **Prettier:** Use Prettier to format your code automatically.
|
||||
* **TypeScript Compiler:** Use the TypeScript compiler to compile your code.
|
||||
* **npm or Yarn:** Use npm or Yarn to manage your dependencies.
|
||||
* **Testing Framework:** Jest is a great testing framework
|
||||
|
||||
### 7.2 Build Configuration
|
||||
|
||||
* **Use a Build Tool:** Use a build tool (e.g., Webpack, Parcel, Rollup) to bundle your code for production.
|
||||
* **Configure the Build Tool:** Configure the build tool to optimize the bundle size, to minify the code, and to perform tree shaking.
|
||||
* **Use Environment Variables:** Use environment variables to configure the build process.
|
||||
|
||||
### 7.3 Linting and Formatting
|
||||
|
||||
* **Configure ESLint:** Configure ESLint to enforce code style and to prevent errors. Use a consistent code style across the entire project.
|
||||
* **Configure Prettier:** Configure Prettier to format your code automatically. This ensures that the code is consistently formatted.
|
||||
* **Use a Pre-Commit Hook:** Use a pre-commit hook to run ESLint and Prettier before committing code. This prevents code with style violations or errors from being committed.
|
||||
|
||||
### 7.4 Deployment Best Practices
|
||||
|
||||
* **Use a Deployment Platform:** Use a deployment platform (e.g., Vercel, Netlify, AWS) to deploy your application.
|
||||
* **Configure the Deployment Platform:** Configure the deployment platform to automatically deploy your application when changes are pushed to the repository.
|
||||
* **Use Environment Variables:** Use environment variables to configure the deployment environment.
|
||||
* **Monitor the Application:** Monitor the application to identify and resolve issues.
|
||||
|
||||
### 7.5 CI/CD Integration
|
||||
|
||||
* **Use a CI/CD Tool:** Use a CI/CD tool (e.g., GitHub Actions, GitLab CI, CircleCI) to automate the build, test, and deployment process.
|
||||
* **Configure the CI/CD Tool:** Configure the CI/CD tool to run tests, build the application, and deploy the application automatically.
|
||||
* **Use Environment Variables:** Use environment variables to configure the CI/CD environment.
|
||||
|
||||
By adhering to these best practices, you can build robust, maintainable, and efficient applications using tRPC.
|
||||
@@ -0,0 +1,65 @@
|
||||
---
|
||||
description: This rule provides best practices for CSS development, covering code organization, performance, security, testing, and common pitfalls. It aims to ensure maintainable, scalable, and efficient CSS code.
|
||||
globs: **/*.css
|
||||
---
|
||||
- **Use a CSS Preprocessor**: Leverage preprocessors like Sass, Less, or Stylus for features like variables, nesting, mixins, and functions to enhance code organization and maintainability.
|
||||
|
||||
- **Code Organization and Structure**:
|
||||
- **Directory Structure**: Organize CSS files into logical directories based on functionality (e.g., `components`, `modules`, `pages`, `themes`).
|
||||
- **File Naming Conventions**: Use meaningful and consistent file names (e.g., `button.css`, `header.module.css`). Consider using a naming convention like BEM (Block, Element, Modifier) or SUIT CSS.
|
||||
- **Module Organization**: Break down large stylesheets into smaller, reusable modules.
|
||||
- **Component Architecture**: Structure CSS based on UI components, ensuring each component has its dedicated stylesheet.
|
||||
- **Code Splitting**: Split CSS into critical (above-the-fold) and non-critical CSS for improved initial page load time. Utilize tools like `Critical CSS` or `PurgeCSS`.
|
||||
|
||||
- **Formatting and Style**:
|
||||
- **Indentation**: Use soft-tabs with two spaces for indentation.
|
||||
- **Trailing Whitespace**: Avoid trailing whitespace.
|
||||
- **Declaration Order**: Maintain a consistent declaration order (e.g., alphabetical, grouping related properties).
|
||||
- **Property Units**: Use appropriate units (e.g., `rem` or `em` for font sizes, `vw` or `%` for responsive layouts).
|
||||
- **Quotation**: Use double quotes for attribute values in selectors.
|
||||
- **Line Length**: Keep lines reasonably short (e.g., under 80-100 characters) for readability.
|
||||
|
||||
- **Common Patterns and Anti-patterns**:
|
||||
- **BEM (Block, Element, Modifier)**: Use BEM or similar methodologies for clear and maintainable class naming.
|
||||
- **Object-Oriented CSS (OOCSS)**: Apply OOCSS principles to create reusable and scalable styles.
|
||||
- **Avoid !important**: Minimize the use of `!important` to prevent specificity conflicts.
|
||||
- **Avoid Inline Styles**: Prefer external stylesheets or embedded styles over inline styles for better maintainability and separation of concerns.
|
||||
- **Don't use IDs for styling**: Avoid using IDs for styling since they are too specific and make styles harder to override.
|
||||
|
||||
- **Understanding CSS Specificity**: Master CSS specificity rules to avoid unexpected style conflicts. Use specific selectors sparingly.
|
||||
|
||||
- **Use Flexible/Relative Units**: Employ relative units like `em`, `rem`, and `vw` for creating responsive designs that adapt to different screen sizes.
|
||||
|
||||
- **Performance Considerations**:
|
||||
- **Optimize Selectors**: Use efficient CSS selectors to minimize rendering time. Avoid overly complex selectors.
|
||||
- **Minify CSS**: Minify CSS files to reduce file size and improve loading times.
|
||||
- **Compress CSS**: Use Gzip or Brotli compression on the server to further reduce CSS file sizes.
|
||||
- **Browser Caching**: Leverage browser caching to store CSS files locally, reducing server load and improving performance.
|
||||
- **Avoid Expensive Properties**: Avoid CSS properties that are computationally expensive (e.g., `filter`, `box-shadow` with large blur radii) when possible.
|
||||
|
||||
- **Security Best Practices**:
|
||||
- **Sanitize User Input**: When using CSS variables based on user input, sanitize the input to prevent CSS injection attacks.
|
||||
- **Content Security Policy (CSP)**: Implement a CSP to control the sources from which CSS can be loaded.
|
||||
|
||||
- **Testing Approaches**:
|
||||
- **Unit Testing**: Use tools like `CSS Modules` or `styled-components` to write unit tests for individual CSS components.
|
||||
- **Visual Regression Testing**: Implement visual regression testing to detect unexpected changes in CSS styles.
|
||||
- **Linting**: Use a CSS linter (e.g., `stylelint`) to enforce coding standards and catch potential errors.
|
||||
|
||||
- **Common Pitfalls and Gotchas**:
|
||||
- **Specificity Conflicts**: Be aware of specificity issues and use tools to visualize and manage CSS specificity.
|
||||
- **Browser Compatibility**: Test CSS across different browsers and versions to ensure compatibility.
|
||||
- **Vendor Prefixes**: Use vendor prefixes when necessary but consider using tools like `autoprefixer` to automate the process.
|
||||
|
||||
- **Tooling and Environment**:
|
||||
- **CSS Linters**: Use `stylelint` to enforce coding standards and identify potential errors.
|
||||
- **CSS Formatters**: Employ tools like `Prettier` to automatically format CSS code consistently.
|
||||
- **Build Tools**: Integrate CSS compilation, minification, and optimization into your build process using tools like `Webpack`, `Parcel`, or `Gulp`.
|
||||
- **CSS Modules**: Use CSS Modules to scope CSS classes locally and avoid naming conflicts.
|
||||
|
||||
- **Additional Tips**:
|
||||
- **Document CSS**: Add comments to explain complex or non-obvious CSS rules.
|
||||
- **Keep CSS DRY (Don't Repeat Yourself)**: Reuse CSS code as much as possible using variables, mixins, and inheritance.
|
||||
- **Regularly Review and Refactor**: Regularly review and refactor CSS code to maintain its quality and prevent code bloat.
|
||||
- **Consider Accessibility**: Ensure CSS styles contribute to website accessibility (e.g., sufficient color contrast, proper use of semantic HTML).
|
||||
- **Use CSS Variables (Custom Properties)**: Use CSS variables for theming and to manage values across your CSS.
|
||||
@@ -0,0 +1,101 @@
|
||||
---
|
||||
description: Comprehensive guide for Tailwind CSS best practices, covering code organization, performance optimization, security considerations, and common pitfalls. This rule provides actionable guidance for developers to build scalable and maintainable Tailwind CSS projects.
|
||||
globs: **/*.{html,js,jsx,ts,tsx,vue}
|
||||
---
|
||||
- Leverage Tailwind's PurgeCSS to remove unused styles in production. Configure `purge` in `tailwind.config.js` to specify files to scan for Tailwind classes. Example:
|
||||
javascript
|
||||
module.exports = {
|
||||
purge: ['./src/**/*.{js,jsx,ts,tsx}', './public/index.html'],
|
||||
darkMode: false, // or 'media' or 'class'
|
||||
theme: {
|
||||
extend: {},
|
||||
},
|
||||
variants: {
|
||||
extend: {},
|
||||
},
|
||||
plugins: [],
|
||||
}
|
||||
|
||||
- Use Tailwind's Configuration File (`tailwind.config.js`) to customize the theme, colors, spacing, breakpoints, and other design tokens. This promotes consistency and maintainability across the project. Avoid hardcoding values directly in the HTML or components.
|
||||
- Adopt a Mobile-First Approach: Design for smaller screens first and then use Tailwind's responsive modifiers (e.g., `md:`, `lg:`) to adapt the layout and styles for larger screens. This improves the user experience on mobile devices and reduces the amount of CSS needed.
|
||||
- Utilize Tailwind UI or other component libraries built with Tailwind CSS to accelerate development and maintain a consistent design language. Customize the components as needed to fit the specific requirements of the project. Alternatively, create your own reusable components.
|
||||
- Optimize for Performance: Be mindful of the number of Tailwind classes used on each element. Consider using `@apply` in CSS or extracting common styles into custom CSS classes to reduce duplication and improve performance. Use `content` variants when needed instead of the `DEFAULT` to control when generated classes are added. For instance, use `content-[url(..)]` instead of `content-[url(..)]`. Configure the JIT mode for faster build times during development.
|
||||
- Stay Organized with Components: Break down the UI into smaller, reusable components. Use a consistent naming convention for components and Tailwind classes. Consider using a component library like Storybook to document and showcase the components.
|
||||
- Integrate with a Design System: Define a clear design system with consistent colors, typography, and spacing. Map the design system tokens to Tailwind's configuration file. This ensures that the UI is consistent and aligned with the brand guidelines.
|
||||
- Use semantic class names: While Tailwind promotes utility-first CSS, consider using semantic class names in conjunction with Tailwind classes to improve readability and maintainability. For example, instead of `<button class="bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded">`, you could use `<button class="primary-button">` and define the corresponding styles in your CSS file using `@apply`. This allows you to update the button styles in one place without having to modify the HTML.
|
||||
- Create Custom Utilities: Extend Tailwind's functionality by creating custom utilities for frequently used CSS patterns. Add these utilities to `tailwind.config.js` under the `extend.utilities` section. This will allow you to apply these patterns with a single class name.
|
||||
- Use the Theme Function: Leverage the `theme()` function in your CSS or JavaScript files to access values defined in `tailwind.config.js`. This ensures that you are using consistent values throughout your project and that changes to the theme are reflected everywhere.
|
||||
- Avoid Inline Styles: Refrain from using inline styles as much as possible. Tailwind provides a comprehensive set of utility classes, so most styling needs can be met without resorting to inline styles. Inline styles can make it harder to maintain and update the styles in your project.
|
||||
- Use Layer Directives: Use `@layer` directives in your CSS to organize your styles and ensure that Tailwind's base styles are applied correctly. This can help prevent conflicts between your custom styles and Tailwind's default styles.
|
||||
- Be Careful with Arbitrary Values: While Tailwind allows you to use arbitrary values with square bracket notation (e.g., `w-[23px]`), use this feature sparingly. Overuse of arbitrary values can make your code less readable and harder to maintain. Prefer using values defined in your `tailwind.config.js` file whenever possible.
|
||||
- Utilize Variants Effectively: Understand and use Tailwind's variants (e.g., `hover:`, `focus:`, `active:`) to create interactive and dynamic styles. Customize the variants in `tailwind.config.js` to match the specific needs of your project.
|
||||
- Code Organization and Structure:
|
||||
- Directory structure: Organize your Tailwind CSS files into a logical directory structure. Common approaches include:
|
||||
- `src/css/`: Contains `tailwind.css` (input file) and other custom CSS files.
|
||||
- `src/components/`: Contains reusable UI components.
|
||||
- `src/layout/`: Contains layout components (e.g., header, footer, navigation).
|
||||
- File naming conventions: Use descriptive and consistent file names. For example:
|
||||
- `button.css`: Styles for a button component.
|
||||
- `header.js`: JavaScript file for a header component.
|
||||
- Module organization: Break down your CSS into smaller, manageable modules. Use `@import` in your `tailwind.css` file to import these modules. This improves code organization and maintainability.
|
||||
- Component architecture: Design your UI with a component-based architecture. Each component should have its own CSS file that defines the styles for that component.
|
||||
- Code splitting strategies: Consider using code splitting to reduce the initial load time of your application. This can be achieved by splitting your CSS into smaller chunks and loading them on demand.
|
||||
- Common Patterns and Anti-patterns:
|
||||
- Design patterns:
|
||||
- Atomic CSS: Tailwind promotes the atomic CSS approach, where styles are applied using small, single-purpose utility classes.
|
||||
- Utility-first CSS: Prioritize using utility classes over custom CSS classes.
|
||||
- Component-based styling: Encapsulate styles within components.
|
||||
- Recommended approaches:
|
||||
- Use a consistent naming convention for your components and CSS classes.
|
||||
- Document your components and styles.
|
||||
- Test your components and styles.
|
||||
- Anti-patterns:
|
||||
- Overusing custom CSS classes: Try to use Tailwind's utility classes as much as possible.
|
||||
- Hardcoding values: Use the theme configuration instead of hardcoding values.
|
||||
- Not using PurgeCSS: This can lead to a large CSS file in production.
|
||||
- State management: Use a state management library like Redux or Zustand to manage the state of your application. Apply tailwind classes based on state changes.
|
||||
- Error handling: Implement proper error handling to catch and handle errors gracefully.
|
||||
- Performance Considerations:
|
||||
- Optimization techniques:
|
||||
- Use PurgeCSS to remove unused styles.
|
||||
- Enable JIT mode.
|
||||
- Optimize images.
|
||||
- Memory management: Be mindful of memory usage, especially when dealing with large datasets or complex UIs.
|
||||
- Rendering optimization: Use techniques like virtualization and memoization to optimize rendering performance.
|
||||
- Bundle size optimization: Reduce the size of your CSS and JavaScript bundles.
|
||||
- Lazy loading: Load resources on demand to improve initial load time.
|
||||
- Security Best Practices:
|
||||
- Common vulnerabilities:
|
||||
- Cross-site scripting (XSS)
|
||||
- Cross-site request forgery (CSRF)
|
||||
- Injection attacks
|
||||
- Input validation: Validate all user input to prevent malicious data from being injected into your application.
|
||||
- Authentication and authorization: Implement proper authentication and authorization mechanisms to protect your application from unauthorized access.
|
||||
- Data protection: Protect sensitive data by encrypting it and storing it securely.
|
||||
- Secure API communication: Use HTTPS to encrypt communication between your application and the server.
|
||||
- Testing Approaches:
|
||||
- Unit testing: Test individual components and functions in isolation.
|
||||
- Integration testing: Test the interaction between different components and modules.
|
||||
- End-to-end testing: Test the entire application from start to finish.
|
||||
- Test organization: Organize your tests into a logical directory structure.
|
||||
- Mocking and stubbing: Use mocking and stubbing to isolate your tests and avoid dependencies on external resources.
|
||||
- Common Pitfalls and Gotchas:
|
||||
- Frequent mistakes:
|
||||
- Not configuring PurgeCSS properly.
|
||||
- Overriding Tailwind's styles without understanding the consequences.
|
||||
- Using arbitrary values excessively.
|
||||
- Edge cases:
|
||||
- Handling different screen sizes and devices.
|
||||
- Dealing with complex layouts and interactions.
|
||||
- Supporting older browsers.
|
||||
- Version-specific issues: Be aware of any version-specific issues and compatibility concerns.
|
||||
- Debugging strategies: Use browser developer tools to inspect the CSS and debug any issues.
|
||||
- Tooling and Environment:
|
||||
- Recommended tools:
|
||||
- Visual Studio Code with the Tailwind CSS IntelliSense extension.
|
||||
- PostCSS with the autoprefixer plugin.
|
||||
- ESLint with the eslint-plugin-tailwindcss plugin.
|
||||
- Build configuration: Configure your build process to use PurgeCSS and optimize your CSS.
|
||||
- Linting and formatting: Use a linter and formatter to enforce code style and catch errors.
|
||||
- Deployment: Deploy your application to a production environment that is optimized for performance and security.
|
||||
- CI/CD: Integrate your application with a CI/CD pipeline to automate the build, test, and deployment process.
|
||||
@@ -0,0 +1,262 @@
|
||||
---
|
||||
description: Enforces best practices for TypeScript development, including coding standards, performance considerations, and common pitfalls. This rule provides actionable guidance for developers to write clean, maintainable, and scalable TypeScript code.
|
||||
globs: **/*.ts?(x)
|
||||
---
|
||||
# TypeScript Best Practices and Coding Standards
|
||||
|
||||
This document outlines best practices and coding standards for developing TypeScript applications. Following these guidelines will help ensure code quality, maintainability, and scalability.
|
||||
|
||||
## 1. Code Organization and Structure
|
||||
|
||||
- **Directory Structure:**
|
||||
- **Feature-based:** Group files related to a specific feature within a dedicated directory.
|
||||
|
||||
src/
|
||||
├── feature1/
|
||||
│ ├── components/
|
||||
│ │ ├── ComponentA.tsx
|
||||
│ │ └── ComponentB.tsx
|
||||
│ ├── services/
|
||||
│ │ └── feature1.service.ts
|
||||
│ ├── types.ts
|
||||
│ └── feature1.module.ts
|
||||
├── feature2/
|
||||
│ └── ...
|
||||
└── shared/
|
||||
├── components/
|
||||
│ └── ReusableComponent.tsx
|
||||
├── services/
|
||||
│ └── api.service.ts
|
||||
└── types/
|
||||
└── global.d.ts
|
||||
|
||||
- **Type-based:** Separate files based on their role (components, services, types, etc.).
|
||||
|
||||
src/
|
||||
├── components/
|
||||
│ ├── Feature1Component.tsx
|
||||
│ └── Feature2Component.tsx
|
||||
├── services/
|
||||
│ ├── feature1.service.ts
|
||||
│ └── feature2.service.ts
|
||||
├── types/
|
||||
│ ├── feature1.types.ts
|
||||
│ └── feature2.types.ts
|
||||
└── modules/
|
||||
├── feature1.module.ts
|
||||
└── feature2.module.ts
|
||||
|
||||
- Choose the structure that best fits your project's complexity and team's preferences. Consistency is key.
|
||||
|
||||
- **File Naming Conventions:**
|
||||
- Use descriptive and consistent file names.
|
||||
- Components: `ComponentName.tsx`
|
||||
- Services: `serviceName.service.ts`
|
||||
- Types: `typeName.types.ts` or `types.ts` (if grouping related types)
|
||||
- Modules: `moduleName.module.ts`
|
||||
- Interfaces: `IInterfaceName.ts` (or `interfaceName.interface.ts` if preferred and consistent throughout the codebase)
|
||||
|
||||
- **Module Organization:**
|
||||
- Use ES Modules (`import`/`export`) for modularity and reusability.
|
||||
- Favor named exports over default exports for better discoverability and refactoring.
|
||||
- Group related functionality into modules.
|
||||
- Avoid circular dependencies.
|
||||
|
||||
- **Component Architecture:**
|
||||
- Consider using component-based architectures like React, Angular, or Vue.js.
|
||||
- Follow component design principles: Single Responsibility Principle, separation of concerns.
|
||||
- Use composition over inheritance.
|
||||
- Keep components small and focused.
|
||||
|
||||
- **Code Splitting Strategies:**
|
||||
- Split your application into smaller chunks to improve initial load time.
|
||||
- Implement lazy loading for modules and components that are not immediately needed.
|
||||
- Use dynamic imports (`import()`).
|
||||
- Webpack, Parcel, and other bundlers offer built-in support for code splitting.
|
||||
|
||||
## 2. Common Patterns and Anti-patterns
|
||||
|
||||
- **Design Patterns:**
|
||||
- **Factory Pattern:** Use factories to create objects with complex initialization logic.
|
||||
- **Singleton Pattern:** Use sparingly, and only when a single instance is truly required.
|
||||
- **Observer Pattern:** Implement reactive patterns for handling events and data changes.
|
||||
- **Strategy Pattern:** Define a family of algorithms and encapsulate each one into a separate class.
|
||||
- **Dependency Injection:** Reduce coupling by injecting dependencies into components and services.
|
||||
|
||||
- **Recommended Approaches:**
|
||||
- **Data Fetching:** Use libraries like `axios` or `fetch` for making API requests.
|
||||
- **State Management:** Choose a state management solution appropriate for your application's complexity (e.g., React Context, Redux, Zustand, MobX).
|
||||
- **Form Handling:** Use libraries like `react-hook-form` or `formik` for managing form state and validation.
|
||||
|
||||
- **Anti-patterns and Code Smells:**
|
||||
- **`any` type overuse:** Avoid using `any` as much as possible. Use more specific types or generics.
|
||||
- **Long methods/functions:** Break down large functions into smaller, more manageable units.
|
||||
- **Deeply nested code:** Refactor deeply nested code to improve readability.
|
||||
- **Magic numbers/strings:** Use constants for values that have a specific meaning.
|
||||
- **Duplicated code:** Extract common logic into reusable functions or components.
|
||||
- **Ignoring errors:** Always handle errors gracefully. Don't just catch and ignore them.
|
||||
- **Over-commenting:** Write self-documenting code and use comments only when necessary to explain complex logic.
|
||||
|
||||
- **State Management Best Practices:**
|
||||
- Choose a state management library based on project needs: React Context API, Redux, Zustand, MobX.
|
||||
- Keep state minimal and derive values where possible.
|
||||
- Follow immutable update patterns (especially with Redux).
|
||||
- Use selectors to access state.
|
||||
- Centralize state logic.
|
||||
|
||||
- **Error Handling Patterns:**
|
||||
- Use `try...catch` blocks to handle potential errors.
|
||||
- Implement a global error handler to catch unhandled exceptions.
|
||||
- Use error logging to track errors in production.
|
||||
- Use discriminated unions for representing different error states.
|
||||
- Implement retry mechanisms for transient errors.
|
||||
|
||||
## 3. Performance Considerations
|
||||
|
||||
- **Optimization Techniques:**
|
||||
- **Memoization:** Use memoization techniques (e.g., `React.memo`, `useMemo`) to avoid unnecessary re-renders.
|
||||
- **Debouncing and Throttling:** Limit the rate at which functions are executed in response to user input.
|
||||
- **Virtualization:** Use virtualization for rendering large lists or tables.
|
||||
- **Code Splitting:** Split your code into smaller chunks to reduce initial load time.
|
||||
|
||||
- **Memory Management:**
|
||||
- Avoid memory leaks by properly cleaning up resources (e.g., event listeners, timers).
|
||||
- Use weak references to avoid circular dependencies that can prevent garbage collection.
|
||||
- Profile your application to identify memory leaks.
|
||||
|
||||
- **Rendering Optimization:**
|
||||
- Minimize DOM manipulations.
|
||||
- Use CSS transforms and animations instead of JavaScript animations.
|
||||
- Optimize images and other assets.
|
||||
- Use the `shouldComponentUpdate` lifecycle method or `React.memo` to prevent unnecessary re-renders.
|
||||
|
||||
- **Bundle Size Optimization:**
|
||||
- Use tree shaking to remove unused code from your bundle.
|
||||
- Minify your code to reduce bundle size.
|
||||
- Compress your code using gzip or Brotli.
|
||||
- Use code splitting to load only the code that is needed for a particular page or component.
|
||||
|
||||
- **Lazy Loading Strategies:**
|
||||
- Lazy load modules and components that are not immediately needed.
|
||||
- Use dynamic imports (`import()`) to load modules on demand.
|
||||
- Implement a loading indicator to provide feedback to the user while the module is loading.
|
||||
|
||||
## 4. Security Best Practices
|
||||
|
||||
- **Common Vulnerabilities and Prevention:**
|
||||
- **Cross-Site Scripting (XSS):** Sanitize user input and escape output to prevent XSS attacks.
|
||||
- **Cross-Site Request Forgery (CSRF):** Use anti-CSRF tokens to protect against CSRF attacks.
|
||||
- **SQL Injection:** Use parameterized queries or ORMs to prevent SQL injection attacks (relevant for backend TypeScript).
|
||||
- **Denial of Service (DoS):** Implement rate limiting and other measures to prevent DoS attacks.
|
||||
- **Man-in-the-Middle (MitM):** Use HTTPS to encrypt communication between the client and server.
|
||||
|
||||
- **Input Validation:**
|
||||
- Validate all user input on both the client and server sides.
|
||||
- Use strong validation rules to prevent malicious input.
|
||||
- Sanitize user input to remove potentially harmful characters.
|
||||
|
||||
- **Authentication and Authorization Patterns:**
|
||||
- Use a secure authentication mechanism to verify user identities.
|
||||
- Implement authorization checks to control access to resources.
|
||||
- Use role-based access control (RBAC) to manage user permissions.
|
||||
- Use JSON Web Tokens (JWT) for stateless authentication.
|
||||
|
||||
- **Data Protection Strategies:**
|
||||
- Encrypt sensitive data at rest and in transit.
|
||||
- Use strong encryption algorithms.
|
||||
- Store passwords securely using a hashing algorithm and salt.
|
||||
- Protect API keys and other secrets.
|
||||
|
||||
- **Secure API Communication:**
|
||||
- Use HTTPS for all API communication.
|
||||
- Implement proper authentication and authorization for API endpoints.
|
||||
- Use rate limiting to prevent abuse.
|
||||
- Validate API requests and responses.
|
||||
|
||||
## 5. Testing Approaches
|
||||
|
||||
- **Unit Testing Strategies:**
|
||||
- Write unit tests for individual functions and components.
|
||||
- Use mocking and stubbing to isolate units of code.
|
||||
- Test edge cases and error conditions.
|
||||
- Aim for high code coverage.
|
||||
|
||||
- **Integration Testing:**
|
||||
- Test the interaction between different modules and components.
|
||||
- Verify that different parts of the application work together correctly.
|
||||
|
||||
- **End-to-End Testing:**
|
||||
- Test the entire application from the user's perspective.
|
||||
- Use tools like Cypress or Playwright to automate end-to-end tests.
|
||||
|
||||
- **Test Organization:**
|
||||
- Organize tests in a way that makes it easy to find and run them.
|
||||
- Group tests by feature or module.
|
||||
- Use descriptive test names.
|
||||
|
||||
- **Mocking and Stubbing:**
|
||||
- Use mocking and stubbing to isolate units of code and simulate dependencies.
|
||||
- Use mocking libraries like Jest or Sinon.js.
|
||||
|
||||
## 6. Common Pitfalls and Gotchas
|
||||
|
||||
- **Frequent Mistakes:**
|
||||
- Incorrectly handling asynchronous operations (Promises, async/await).
|
||||
- Not handling errors properly.
|
||||
- Overusing the `any` type.
|
||||
- Ignoring compiler warnings.
|
||||
- Not keeping dependencies up to date.
|
||||
|
||||
- **Edge Cases:**
|
||||
- Handling different browser versions and devices.
|
||||
- Dealing with network latency and failures.
|
||||
- Handling different time zones and locales.
|
||||
- Handling large datasets and complex calculations.
|
||||
|
||||
- **Version-Specific Issues:**
|
||||
- Be aware of breaking changes in new versions of TypeScript and related libraries.
|
||||
- Consult the release notes for each new version to identify potential issues.
|
||||
- Use TypeScript's compiler options to target specific ECMAScript versions and maintain backwards compatibility if needed.
|
||||
|
||||
- **Compatibility Concerns:**
|
||||
- Ensure that your code is compatible with the target browsers and devices.
|
||||
- Use polyfills to provide support for older browsers.
|
||||
- Test your code on different platforms to identify compatibility issues.
|
||||
|
||||
- **Debugging Strategies:**
|
||||
- Use a debugger to step through your code and inspect variables.
|
||||
- Use console logging to track the flow of execution and identify errors.
|
||||
- Use TypeScript's type checking to catch errors early.
|
||||
- Use source maps to debug code that has been transpiled or minified.
|
||||
- Learn to read and understand stack traces.
|
||||
|
||||
## 7. Tooling and Environment
|
||||
|
||||
- **Recommended Development Tools:**
|
||||
- **IDE:** Visual Studio Code with the TypeScript extension.
|
||||
- **Package Manager:** npm or Yarn.
|
||||
- **Bundler:** Webpack, Parcel, or Rollup.
|
||||
- **Linter:** ESLint with TypeScript-specific rules.
|
||||
- **Formatter:** Prettier.
|
||||
- **Testing Framework:** Jest, Mocha, or Jasmine.
|
||||
|
||||
- **Build Configuration:**
|
||||
- Use a `tsconfig.json` file to configure the TypeScript compiler.
|
||||
- Configure compiler options like `target`, `module`, `jsx`, and `strict`.
|
||||
- Use TypeScript's project references to organize large projects.
|
||||
|
||||
- **Linting and Formatting:**
|
||||
- Use ESLint with TypeScript-specific rules to enforce coding standards.
|
||||
- Use Prettier to automatically format your code.
|
||||
- Integrate linting and formatting into your development workflow using Git hooks or CI/CD pipelines.
|
||||
|
||||
- **Deployment Best Practices:**
|
||||
- Use a build process to transpile and bundle your code.
|
||||
- Minify and compress your code to reduce bundle size.
|
||||
- Use a CDN to serve static assets.
|
||||
- Implement caching strategies to improve performance.
|
||||
|
||||
- **CI/CD Integration:**
|
||||
- Integrate your tests and linters into your CI/CD pipeline.
|
||||
- Automate the build and deployment process.
|
||||
- Use environment variables to configure your application for different environments.
|
||||
@@ -0,0 +1,145 @@
|
||||
---
|
||||
description: This rule provides comprehensive guidelines for using the Zod library effectively, covering code organization, performance, security, and testing to ensure robust and maintainable type validation.
|
||||
globs: **/*.ts?(x)
|
||||
---
|
||||
- **Organize Zod schemas logically for readability and maintainability.** Group related schemas together and structure your Zod code for improved clarity, especially in larger projects.
|
||||
- **Compose and reuse related schemas to avoid repetition.** Use Zod's composition features (e.g., `z.intersection`, `z.union`, `z.extend`) to create reusable schema components and reduce redundancy.
|
||||
- **Implement schema versioning for better management.** As your application evolves, version your schemas to handle data migrations and maintain compatibility with older data formats.
|
||||
- **Use Zod for type-safe data validation and transformation.** Leverage Zod's capabilities for both validating and transforming data to ensure data integrity throughout your application.
|
||||
|
||||
### 1. Code Organization and Structure:
|
||||
|
||||
- **Directory Structure Best Practices:**
|
||||
- Consider grouping Zod schemas within dedicated directories (e.g., `schemas/`, `models/schemas/`).
|
||||
- Organize schemas by domain, feature, or data model.
|
||||
- Use subdirectories for complex schemas or schema families.
|
||||
- **File Naming Conventions:**
|
||||
- Name schema files descriptively (e.g., `user.schema.ts`, `product.schema.ts`).
|
||||
- Use a consistent naming pattern throughout the project.
|
||||
- Consider including the data model name or the schema's purpose in the filename.
|
||||
- **Module Organization:**
|
||||
- Export schemas as named exports from each module.
|
||||
- Create index files (e.g., `index.ts`) to re-export schemas from subdirectories for easier access.
|
||||
- Use clear and concise module names.
|
||||
- **Component Architecture:**
|
||||
- If you are building React components, consider creating a `components/schemas/` directory where you house your schema related to specific components.
|
||||
- Use Zod to validate the props passed to React components using `z.infer` and `z.ZodType<Props>`
|
||||
- You can create a custom hook that handles validation with Zod and stores the parsed result in React state.
|
||||
- **Code Splitting Strategies:**
|
||||
- For large schema definitions, split them into smaller, more manageable files.
|
||||
- Use Zod's composition features to combine these smaller schemas into larger, more complex schemas as needed.
|
||||
|
||||
### 2. Common Patterns and Anti-patterns:
|
||||
|
||||
- **Design Patterns Specific to Zod:**
|
||||
- **Schema Composition:** Use `z.intersection`, `z.union`, `z.extend`, and `z.optional` to combine and modify existing schemas.
|
||||
- **Schema Transformation:** Use `.transform` to modify data during validation.
|
||||
- **Custom Validation:** Use `.refine` and `.superRefine` for custom validation logic.
|
||||
- **Default Values:** Use `.default` to assign default values to schema properties.
|
||||
- **Recommended Approaches for Common Tasks:**
|
||||
- **Form Validation:** Use Zod to validate form input data and display errors.
|
||||
- **API Request Validation:** Use Zod to validate incoming API request bodies.
|
||||
- **Data Serialization/Deserialization:** Use Zod to validate and transform data when serializing or deserializing.
|
||||
- **Anti-patterns and Code Smells to Avoid:**
|
||||
- **Overly Complex Schemas:** Avoid creating schemas that are too complex or difficult to understand. Break them down into smaller, more manageable schemas.
|
||||
- **Ignoring Validation Errors:** Always handle validation errors and provide informative feedback to the user.
|
||||
- **Duplicated Schema Definitions:** Avoid duplicating schema definitions. Use schema composition to reuse existing schemas.
|
||||
- **State Management Best Practices:**
|
||||
- When using Zod with state management libraries (e.g., Redux, Zustand), validate the state data using Zod schemas.
|
||||
- Use Zod to validate state updates before applying them to the state.
|
||||
- **Error Handling Patterns:**
|
||||
- Use Zod's `.safeParse` method to handle validation errors gracefully.
|
||||
- Provide informative error messages to the user.
|
||||
- Log validation errors for debugging purposes.
|
||||
|
||||
### 3. Performance Considerations:
|
||||
|
||||
- **Optimization Techniques:**
|
||||
- **Schema Caching:** Cache frequently used schemas to avoid re-parsing them.
|
||||
- **Pre-compilation:** If possible, pre-compile schemas during build time to improve performance.
|
||||
- **Minimize Schema Complexity:** Keep schemas as simple as possible to reduce validation overhead.
|
||||
- **Memory Management:**
|
||||
- Be mindful of the memory usage of large schemas, especially when dealing with large datasets.
|
||||
- Release unused schemas when they are no longer needed.
|
||||
- **Bundle Size Optimization:**
|
||||
- Remove unused schemas and code from the bundle.
|
||||
- Use tree shaking to eliminate dead code.
|
||||
- **Lazy Loading Strategies:**
|
||||
- Lazily load schemas that are not immediately needed.
|
||||
- Use code splitting to load schemas on demand.
|
||||
|
||||
### 4. Security Best Practices:
|
||||
|
||||
- **Common Vulnerabilities and How to Prevent Them:**
|
||||
- **Injection Attacks:** Prevent injection attacks by validating and sanitizing user input data.
|
||||
- **Cross-Site Scripting (XSS):** Prevent XSS attacks by encoding user input data before displaying it in the UI.
|
||||
- **Denial of Service (DoS):** Prevent DoS attacks by limiting the size and complexity of input data.
|
||||
- **Input Validation:**
|
||||
- Validate all user input data using Zod schemas.
|
||||
- Enforce strict validation rules to prevent invalid or malicious data from entering the system.
|
||||
- **Authentication and Authorization Patterns:**
|
||||
- Use Zod to validate user credentials during authentication.
|
||||
- Use Zod to validate authorization tokens and permissions.
|
||||
- **Data Protection Strategies:**
|
||||
- Encrypt sensitive data at rest and in transit.
|
||||
- Use secure storage mechanisms to protect data from unauthorized access.
|
||||
- **Secure API Communication:**
|
||||
- Use HTTPS to encrypt API communication.
|
||||
- Validate API request and response data using Zod schemas.
|
||||
|
||||
### 5. Testing Approaches:
|
||||
|
||||
- **Unit Testing Strategies:**
|
||||
- Write unit tests for individual schemas to ensure they validate data correctly.
|
||||
- Test different input scenarios, including valid and invalid data.
|
||||
- Use mocking and stubbing to isolate schemas from external dependencies.
|
||||
- **Integration Testing:**
|
||||
- Write integration tests to ensure that schemas work correctly with other parts of the application.
|
||||
- Test the interaction between schemas and data sources (e.g., databases, APIs).
|
||||
- **End-to-End Testing:**
|
||||
- Write end-to-end tests to ensure that the entire application works correctly with Zod schemas.
|
||||
- Test the user interface and the data flow through the application.
|
||||
- **Test Organization:**
|
||||
- Organize tests into separate directories based on the type of test (e.g., unit, integration, end-to-end).
|
||||
- Use descriptive test names to indicate the purpose of each test.
|
||||
- **Mocking and Stubbing:**
|
||||
- Use mocking and stubbing to isolate schemas from external dependencies during testing.
|
||||
- Mock data sources and APIs to control the test environment.
|
||||
|
||||
### 6. Common Pitfalls and Gotchas:
|
||||
|
||||
- **Frequent Mistakes Developers Make:**
|
||||
- **Incorrect Schema Definitions:** Ensure that schema definitions accurately reflect the expected data format.
|
||||
- **Ignoring Validation Errors:** Always handle validation errors and provide informative feedback to the user.
|
||||
- **Overly Complex Schemas:** Avoid creating schemas that are too complex or difficult to understand.
|
||||
- **Edge Cases to Be Aware Of:**
|
||||
- **Null and Undefined Values:** Handle null and undefined values correctly in schemas.
|
||||
- **Empty Strings and Arrays:** Handle empty strings and arrays appropriately.
|
||||
- **Date and Time Formats:** Use consistent date and time formats throughout the application.
|
||||
- **Version-Specific Issues:**
|
||||
- Be aware of any version-specific issues or breaking changes in Zod.
|
||||
- Refer to the Zod documentation and release notes for information on compatibility and migration.
|
||||
- **Compatibility Concerns:**
|
||||
- Ensure that Zod schemas are compatible with the data formats used by other systems or libraries.
|
||||
- Consider using a data serialization format (e.g., JSON, YAML) that is widely supported.
|
||||
- **Debugging Strategies:**
|
||||
- Use Zod's `.safeParse` method to log validation errors for debugging purposes.
|
||||
- Use a debugger to step through the validation process and identify issues.
|
||||
|
||||
### 7. Tooling and Environment:
|
||||
|
||||
- **Recommended Development Tools:**
|
||||
- **TypeScript:** Use TypeScript to provide static typing for Zod schemas and data.
|
||||
- **VS Code:** Use VS Code with the Zod extension for improved code completion and validation.
|
||||
- **Build Configuration:**
|
||||
- Configure the build process to transpile TypeScript code and bundle JavaScript code.
|
||||
- Use a module bundler (e.g., Webpack, Parcel, Rollup) to optimize the bundle size.
|
||||
- **Linting and Formatting:**
|
||||
- Use a linter (e.g., ESLint) to enforce code style and best practices.
|
||||
- Use a code formatter (e.g., Prettier) to automatically format code.
|
||||
- **Deployment Best Practices:**
|
||||
- Deploy the application to a production environment with appropriate security measures in place.
|
||||
- Monitor the application for errors and performance issues.
|
||||
- **CI/CD Integration:**
|
||||
- Integrate Zod schemas into the CI/CD pipeline to automate validation and testing.
|
||||
- Run unit tests, integration tests, and end-to-end tests as part of the CI/CD process.
|
||||
Reference in New Issue
Block a user