Regenerate all MDC rules with fresh Exa data and December 2025 best practices

- Refreshed all 241 library rules with current best practices
- Updated Exa search results for all libraries with 2025 content
- Fixed --regenerate-all flag logic to properly process all libraries
- Removed duplicate astro entry in rules.json (merged tags)
- Added missing docker.mdc and vim.mdc files
- All rules now include modern patterns and anti-patterns
- Updated with framework-specific recommendations for 2025

Technical improvements:
- Fixed retry_failed_only logic in generate_mdc_files.py
- Improved progress tracking for regeneration scenarios
- Ensured proper handling of --refresh-exa flag
This commit is contained in:
sanjeed5
2025-12-17 22:40:28 +05:30
parent 331fb6ffac
commit 8fbf269085
244 changed files with 66701 additions and 52708 deletions
+155 -282
View File
@@ -1,284 +1,157 @@
---
description: This rule file outlines best practices for integrating Stripe's payment processing services into web and mobile applications, focusing on security, performance, and maintainability. It provides guidelines on coding standards, error handling, and testing to ensure a robust and reliable Stripe integration.
globs: *.js,*.jsx,*.ts,*.tsx,*.py,*.rb,*.php,*.java,*.go
description: Definitive guidelines for building robust, secure, and efficient Stripe integrations using modern API practices (v2, Checkout Sessions, Payment Intents, Elements) and essential safeguards like idempotency and webhook verification.
globs: **/*
---
# Stripe Integration Best Practices
This document provides a comprehensive guide to best practices for integrating Stripe's payment processing services. It covers code organization, common patterns, performance considerations, security, testing, common pitfalls, and tooling.
## Library Information:
- Name: stripe
- Tags: payments, api, e-commerce, financial
## 1. Code Organization and Structure
### 1.1 Directory Structure Best Practices
Organizing your project effectively enhances maintainability and readability. Consider the following structure:
project-root/
├── src/
│ ├── components/ # Reusable UI components (if applicable)
│ ├── services/
│ │ └── stripe/ # Stripe-related services
│ │ ├── payments.js/ts # Payment processing logic
│ │ ├── subscriptions.js/ts # Subscription management
│ │ ├── webhooks.js/ts # Webhook handling
│ │ ├── utils.js/ts # Utility functions
│ ├── models/ # Data models and types
│ ├── config/ # Configuration files (API keys, etc.)
│ ├── utils/ # General utility functions
├── tests/ # Test suites
├── .env # Environment variables
└── ...
* `components`: If you're building a UI, this directory holds reusable UI components. This might include components that display payment forms or payment status indicators.
* `services/stripe`: This directory encapsulates all Stripe-related interactions. This promotes separation of concerns and makes it easier to update or replace the Stripe integration in the future.
* `payments.js/ts`: Contains functions for creating charges, handling payment intents, and processing refunds.
* `subscriptions.js/ts`: Includes logic for creating, updating, and canceling subscriptions.
* `webhooks.js/ts`: Handles incoming Stripe webhook events. Crucially important for asynchronous payment flows.
* `utils.js/ts`: Contains utility functions, such as formatting currency or validating data.
* `models`: Defines data models for Stripe objects (e.g., Customer, Charge, PaymentIntent). This can be useful for type checking and data validation.
* `config`: Stores configuration settings, including your Stripe API keys. Never commit your secret keys to version control. Use environment variables.
* `utils`: General utility functions used throughout your application.
* `tests`: Contains unit and integration tests for your Stripe integration.
### 1.2 File Naming Conventions
* Use descriptive names for files and functions.
* Follow the naming conventions of your chosen language (e.g., camelCase in JavaScript, snake_case in Python).
* Example:
* `stripePayments.js` (JavaScript)
* `stripe_payments.py` (Python)
* `StripePayments.java` (Java)
### 1.3 Module Organization
* Break down your Stripe integration into smaller, reusable modules.
* Use clear and consistent naming conventions for modules.
* Export only the necessary functions and classes from each module to maintain a clean API.
### 1.4 Component Architecture (If Applicable)
* If building a UI, design reusable components for payment forms, payment status displays, and other Stripe-related elements.
* Use a component-based framework (e.g., React, Vue.js, Angular) to manage UI complexity.
* Consider using a state management library (e.g., Redux, Zustand, Vuex) to manage Stripe-related state.
### 1.5 Code Splitting Strategies
* Lazy-load Stripe-related code to reduce the initial bundle size of your application.
* Dynamically import modules containing Stripe-specific logic only when they are needed.
* Use code splitting features provided by your bundler (e.g., Webpack, Parcel) to separate Stripe code into its own chunk.
## 2. Common Patterns and Anti-patterns
### 2.1 Design Patterns
* **Facade:** Create a facade to simplify the Stripe API and provide a higher-level interface for your application.
* **Adapter:** Use an adapter to map data between your application's data model and Stripe's data model.
* **Strategy:** Implement a strategy pattern to handle different payment methods.
* **Observer:** Implement an observer pattern with webhooks. When certain events occur in Stripe, your application gets notified by the Observer (Stripe's Webhooks).
### 2.2 Recommended Approaches for Common Tasks
* **Creating a Charge:** Use Payment Intents for new integrations, and migrate from Charges if possible. Payment Intents handle SCA and other authentication requirements more gracefully.
* **Handling Webhooks:** Implement robust webhook handling with retries and proper error handling.
* **Managing Subscriptions:** Use Stripe's Subscription API to manage recurring payments.
* **Storing Card Details:** Use Stripe Elements to securely collect and tokenize card details.
* **Handling Errors:** Implement comprehensive error handling to gracefully handle API errors.
### 2.3 Anti-patterns and Code Smells
* **Storing API Keys in Client-Side Code:** Never expose your secret API keys in client-side code. All server side interaction only.
* **Directly Accessing the Stripe API from UI Components:** Introduce a service layer to decouple UI components from Stripe API calls.
* **Ignoring Webhook Events:** Always handle webhook events to ensure that your application is synchronized with Stripe's state.
* **Not Validating Input:** Always validate user input to prevent security vulnerabilities.
* **Creating CHARGES directly:** Prefer PaymentIntents which abstract away much of the complexity and make the code future-proof.
### 2.4 State Management
* Use a state management library (e.g., Redux, Zustand, Vuex) to manage Stripe-related state in UI applications.
* Store only the necessary data in the state to minimize memory usage.
* Use immutable data structures to simplify state updates and prevent unexpected side effects.
### 2.5 Error Handling
* Implement comprehensive error handling to gracefully handle API errors.
* Log errors to a central location for monitoring and debugging.
* Provide informative error messages to the user.
* Implement retry logic for transient errors.
* Handle specific Stripe errors (e.g., card declined, invalid API key) appropriately.
## 3. Performance Considerations
### 3.1 Optimization Techniques
* Cache frequently accessed data to reduce API calls.
* Use Stripe's pagination features to retrieve large datasets in smaller chunks.
* Optimize database queries to improve performance.
* Minimize the number of API calls required to complete a task.
* Use webhooks to avoid polling the Stripe API.
### 3.2 Memory Management
* Avoid storing large amounts of Stripe data in memory.
* Use pagination to retrieve large datasets in smaller chunks.
* Release resources when they are no longer needed.
### 3.3 Rendering Optimization (If Applicable)
* Optimize UI components to minimize rendering time.
* Use techniques such as virtualization and memoization to improve rendering performance.
* Avoid re-rendering components unnecessarily.
### 3.4 Bundle Size Optimization
* Use code splitting to reduce the initial bundle size of your application.
* Remove unused code from your Stripe integration.
* Use a minifier to reduce the size of your code.
### 3.5 Lazy Loading
* Lazy-load Stripe-related code to reduce the initial bundle size of your application.
* Dynamically import modules containing Stripe-specific logic only when they are needed.
## 4. Security Best Practices
### 4.1 Common Vulnerabilities and Prevention
* **Cross-Site Scripting (XSS):** Sanitize user input to prevent XSS attacks. Use Stripe Elements to securely collect card details.
* **Cross-Site Request Forgery (CSRF):** Protect against CSRF attacks by using anti-CSRF tokens.
* **SQL Injection:** Use parameterized queries to prevent SQL injection attacks.
* **API Key Exposure:** Never expose your secret API keys in client-side code. Store API Keys as environment variables on a secure server.
* **Man-in-the-Middle Attacks:** Enforce HTTPS to protect against man-in-the-middle attacks.
### 4.2 Input Validation
* Validate all user input to prevent security vulnerabilities.
* Use strong validation rules to ensure that data is valid.
* Sanitize user input to remove malicious characters.
### 4.3 Authentication and Authorization
* Use Stripe's API keys to authenticate requests.
* Use restricted API keys for granular permissions.
* Implement role-based access control to restrict access to sensitive data.
### 4.4 Data Protection
* Use Stripe Elements to securely collect and tokenize card details.
* Encrypt sensitive data at rest and in transit.
* Follow PCI DSS compliance guidelines.
* Regularly review your security practices to mitigate risks.
* Implement tokenization to protect sensitive payment information.
### 4.5 Secure API Communication
* Enforce HTTPS for all API communication.
* Use TLS 1.2 or higher.
* Verify the authenticity of Stripe's servers using SSL/TLS certificates.
## 5. Testing Approaches
### 5.1 Unit Testing
* Write unit tests for individual components and functions in your Stripe integration.
* Use mocking and stubbing to isolate components from external dependencies.
* Test edge cases and error conditions.
### 5.2 Integration Testing
* Write integration tests to verify that different parts of your Stripe integration work together correctly.
* Test the interaction between your application and the Stripe API.
* Use a test Stripe account to avoid affecting live data.
### 5.3 End-to-End Testing
* Write end-to-end tests to verify that your Stripe integration works correctly from the user's perspective.
* Use a testing framework such as Cypress or Selenium to automate end-to-end tests.
### 5.4 Test Organization
* Organize your tests into logical suites based on functionality.
* Use clear and consistent naming conventions for tests.
* Run tests automatically as part of your CI/CD pipeline.
### 5.5 Mocking and Stubbing
* Use mocking and stubbing to isolate components from external dependencies.
* Mock the Stripe API to simulate different scenarios and error conditions.
* Use a mocking library such as Jest or Sinon.js.
## 6. Common Pitfalls and Gotchas
### 6.1 Frequent Mistakes
* **Not Handling Webhooks:** Failing to handle webhook events can lead to inconsistent data and missed events.
* **Storing API Keys in Client-Side Code:** Exposing your secret API keys in client-side code can compromise your account.
* **Not Validating Input:** Failing to validate user input can lead to security vulnerabilities.
* **Using Test Data in Production:** Using test data in a live environment can lead to incorrect transactions and data corruption.
* **Ignoring Error Messages:** Treat stripe error messages as a core part of the functionality. Do not display generic error messages.
### 6.2 Edge Cases
* **Idempotency:** Handle requests carefully by using idempotency keys. These keys ensure that accidental duplicate requests do not result in unexpected behavior, like multiple charges for the same transaction.
* **Network Errors:** Handle network errors gracefully by implementing retry logic.
* **Rate Limiting:** Be aware of Stripe's rate limits and implement a backoff strategy.
* **Concurrency:** Handle concurrent requests carefully to avoid race conditions.
* **SCA (Strong Customer Authentication):** Handle SCA requirements for European customers.
### 6.3 Version-Specific Issues
* Be aware of breaking changes in new versions of the Stripe API.
* Test your integration thoroughly after upgrading to a new version of the Stripe API.
* Use Stripe's API versioning feature to maintain compatibility with older versions of the API.
### 6.4 Compatibility Concerns
* Ensure that your Stripe integration is compatible with all supported browsers and devices.
* Test your integration on different platforms to identify compatibility issues.
### 6.5 Debugging Strategies
* Use Stripe's logging features to track API requests and responses.
* Use a debugger to step through your code and identify errors.
* Use Stripe's API explorer to test API requests.
* Consult Stripe's documentation and support resources.
## 7. Tooling and Environment
### 7.1 Recommended Development Tools
* **IDE:** Visual Studio Code, IntelliJ IDEA, or similar.
* **Testing Framework:** Jest, Mocha, or similar.
* **Mocking Library:** Jest, Sinon.js, or similar.
* **Bundler:** Webpack, Parcel, or similar.
* **Linting:** ESLint, Pylint, or similar.
* **Formatter:** Prettier, Black, or similar.
* **Stripe CLI:** Stripe Command Line Interface is incredibly valuable.
### 7.2 Build Configuration
* Use a build tool to automate the build process.
* Configure your build tool to minify and optimize your code.
* Use environment variables to store configuration settings.
### 7.3 Linting and Formatting
* Use a linter to enforce code style and identify potential errors.
* Use a formatter to automatically format your code.
* Configure your editor to automatically lint and format your code on save.
### 7.4 Deployment
* Deploy your application to a secure server.
* Use HTTPS to encrypt communication between your application and the server.
* Monitor your application for errors and performance issues.
### 7.5 CI/CD Integration
* Use a CI/CD pipeline to automate the build, test, and deployment process.
* Run tests automatically as part of your CI/CD pipeline.
* Use a deployment tool such as Docker to package and deploy your application.
# Stripe Best Practices
This guide outlines the definitive best practices for integrating Stripe into our applications. Adhere to these rules to ensure secure, performant, and maintainable payment flows. Always target the latest Stripe API version (`2025-12-15.clover` as of this writing) and keep SDKs up-to-date.
## 1. Code Organization & Structure
### 1.1. Secure API Key Management
Never hardcode API keys. Store them securely in environment variables.
❌ BAD:
```javascript
const stripe = require('stripe')('sk_test_YOUR_SECRET_KEY');
```
✅ GOOD:
```javascript
// .env
// STRIPE_SECRET_KEY=sk_test_YOUR_SECRET_KEY
const stripe = require('stripe')(process.env.STRIPE_SECRET_KEY);
```
### 1.2. Stripe Client Initialization
Initialize the Stripe client once per process or module. Avoid re-initializing on every request to prevent resource overhead.
✅ GOOD (Node.js example):
```javascript
// lib/stripeClient.js
const stripe = require('stripe')(process.env.STRIPE_SECRET_KEY, {
apiVersion: '2025-12-15', // Pin to a specific API version
});
module.exports = stripe;
// In your service/route handler:
const stripe = require('../lib/stripeClient');
// ... use stripe for all API calls
```
## 2. Common Patterns & Anti-patterns
### 2.1. Modern Checkout Flows
Always use Stripe Checkout Sessions or Payment Intents with Stripe Elements for UI. These handle complex authentication, multi-currency, and compliance automatically, significantly reducing your PCI scope.
❌ BAD: Building custom card input fields and handling raw card data directly on your server.
```javascript
// Avoid handling raw card data on your server
const charge = await stripe.charges.create({ /* ... */ });
```
✅ GOOD: Use Checkout Sessions for pre-built, hosted pages, or Payment Intents + Elements for custom UI.
```javascript
// Server-side (Checkout Session example)
const session = await stripe.checkout.sessions.create({
line_items: [{ price: 'price_123', quantity: 1 }],
mode: 'payment',
success_url: 'https://example.com/success',
cancel_url: 'https://example.com/cancel',
});
// Redirect user to session.url
```
```javascript
// Server-side (Payment Intent example for custom UI)
const paymentIntent = await stripe.paymentIntents.create({
amount: 1000,
currency: 'usd',
automatic_payment_methods: { enabled: true },
});
// Send paymentIntent.client_secret to frontend to use with Stripe Elements
```
### 2.2. Idempotency for Write Operations
Always include a unique `Idempotency-Key` header for all write requests (e.g., creating charges, customers, refunds). This prevents duplicate operations during network retries.
❌ BAD:
```javascript
await stripe.paymentIntents.create({ amount: 1000, currency: 'usd' });
```
✅ GOOD: Generate a stable, unique key per request (e.g., UUID, or a hash of request parameters + user ID).
```javascript
const { v4: uuidv4 } = require('uuid'); // npm install uuid
// ...
await stripe.paymentIntents.create(
{ amount: 1000, currency: 'usd' },
{ idempotencyKey: uuidv4() } // Use a stable key for retries
);
```
### 2.3. Metadata for Traceability
Attach relevant metadata to Stripe objects (charges, customers, Payment Intents) for easier debugging, reconciliation, and integrating with internal business logic.
✅ GOOD:
```javascript
await stripe.paymentIntents.create({
amount: 2000,
currency: 'usd',
metadata: {
order_id: 'ORDER-XYZ-123',
user_id: 'user_abc',
product_sku: 'PROD-001',
},
});
```
### 2.4. API Versioning
Pin your API version in the Stripe client initialization and for webhook endpoints. Regularly upgrade to benefit from new features and security patches, testing thoroughly.
❌ BAD: Relying on Stripe's default API version, which might change unexpectedly.
```javascript
const stripe = require('stripe')(process.env.STRIPE_SECRET_KEY); // No apiVersion specified
```
✅ GOOD: Explicitly set the `apiVersion`.
```javascript
const stripe = require('stripe')(process.env.STRIPE_SECRET_KEY, {
apiVersion: '2025-12-15', // Pin to the latest stable version
});
// Ensure webhook endpoints also use this version in the Dashboard
```
## 3. Error Handling
### 3.1. Catch Specific Stripe Errors
Handle different `StripeError` subclasses to provide precise feedback to users and implement appropriate retry logic. Always log the `requestId`.
✅ GOOD:
```javascript
try {
await stripe.paymentIntents.confirm(paymentIntentId);
} catch (e) {
if (e.type === 'StripeCardError') {
console.error(`Card declined: ${e.message} (Code: ${e.code}, Req ID: ${e.requestId})`);
// Inform user, prompt for new card
} else if (e.type === 'StripeInvalidRequestError') {
console.error(`Invalid request: ${e.message} (Param: ${e.param}, Req ID: ${e.requestId})`);
// Log, alert dev team for code fix
} else {
console.error(`Generic Stripe error: ${e.message} (Req ID: ${e.requestId})`);
// Log, alert dev team, potentially retry for transient errors
}
}
```
### 3.2. Webhook-Driven Error Handling
For asynchronous events (e.g., payment failures after initial confirmation), rely on webhooks. Your server should be the source of truth for payment status updates.
✅ GOOD:
```javascript
// In your webhook handler for 'payment_intent.payment_failed'
app.post('/webhook', async (req, res) => { /* ... signature verification ... */
if (event.type === 'payment_intent.payment_failed') {
const paymentIntent = event.data.object;
console.error(`Payment Intent ${paymentIntent.id} failed: ${paymentIntent.last_payment_error?.message}`);
// Update order status in DB, notify customer, trigger