pocketbase-best-practices
Audited by Runlayer on Feb 21, 2026
Malicious tool definition detected
Tool: AGENTS.md Description: # PocketBase Best Practices **Version 1.1.0** Community January 2026 > Comprehensive PocketBase development best practices and performance optimization guide. Contains rules across 8 categories, prioritized by impact from critical (collection design, API rules, authentication) to incremental (production deployment).
Malicious tool definition detected
Tool: SKILL.md Description: --- name: pocketbase-best-practices description: PocketBase development best practices covering collection design, API rules, authentication, SDK usage, query optimization, realtime subscriptions, file handling, and deployment.
Malicious tool definition detected
Tool: metadata.json Description: { "version": "1.1.0", "organization": "Community", "date": "January 2026", "abstract": "Comprehensive PocketBase development best practices and performance optimization guide.
Malicious tool definition detected
Tool: references/api-rules-security.md [1/2] Description: # API Rules & Security **Impact: CRITICAL** Access control rules, filter expressions, request context usage, and security patterns.
Tool: references/api-rules-security.md [2/2] Description: `<` `<=` | Comparison | | `~` | Contains (LIKE %value%) | | `!~` | Does not contain | | `?=` `?!=` `?>` `?~` | Any element matches | | `&&` | AND | | `\|\|` | OR | | `()` | Grouping | **Date macros:** - `@now` - Current UTC datetime - `@today` - Start of today UTC - `@month` - Start of current month UTC - `@year` - Start of current year UTC Reference: [PocketBase Filters](https://pocketbase.io/docs/api-rules-and-filters/#filters-syntax) #
Malicious tool definition detected
Tool: references/authentication.md [1/3] Description: # Authentication **Impact: CRITICAL** Password authentication, OAuth2 integration, token management, MFA setup, and auth collection configuration.
Tool: references/authentication.md [2/3] Description: OAuth2 (recommended for web apps) async function loginWithOAuth2(providerName) { try { const authData = await pb.collection('users').authWithOAuth2({ provider: providerName, // 'google', 'github', 'microsoft', etc.
Tool: references/authentication.md [3/3]
Malicious tool definition detected
Tool: references/collection-design.md [1/2] Description: # Collection Design **Impact: CRITICAL** Schema design, field types, relations, indexes, and collection type selection.
Tool: references/collection-design.md [2/2] Description: (use multiple fields for routes) Reference: [PocketBase GeoPoint](https://pocketbase.io/docs/collections/#geopoint) ## 4.
Malicious tool definition detected
Tool: references/file-handling.md [1/2] Description: # File Handling **Impact: MEDIUM** File uploads, URL generation, thumbnail creation, and validation patterns.
Tool: references/file-handling.md [2/2] Description: 1024 / 1024}MB`); } if (!allowedTypes.includes(file.type)) { errors.push(`Invalid file type: ${file.type}`); } if (file.name.length > maxNameLength) { errors.push(`Filename too long`); } return { valid: errors.length === 0, errors }; } // Complete upload flow async function handleFileUpload(inputEvent) { const file = inputEvent.target.files[0]; if (!file) return; // Validate const validation = validateFile(file, { maxSize: 5 * 1024 * 1024, all
Malicious tool definition detected
Tool: references/production-deployment.md [1/3] Description: # Production & Deployment **Impact: LOW-MEDIUM** Backup strategies, configuration management, reverse proxy setup, and SQLite optimization.
Tool: references/production-deployment.md [2/3] Description: Default 10, adjust based on needs - **Exempt endpoints**: Optionally whitelist certain paths **Configure programmatically (Go/JS hooks):** ```javascript // In pb_hooks/rate_limit.pb.js routerAdd("GET", "/api/public/*", (e) => { // Custom rate limit for specific endpoints }, $apis.rateLimit(100, "10s")); // 100 requests per 10 seconds // Stricter limit for auth endpoints routerAdd("POST", "/api/collections/users/auth-*", (e) => { // Aut
Tool: references/production-deployment.md [3/3] Description: separate databases: `data.db` (application data) and `auxiliary.db` (logs and ephemeral data), which reduces write contention.
Malicious tool definition detected
Tool: references/query-performance.md [1/4] Description: # Query Performance **Impact: HIGH** Pagination strategies, relation expansion, field selection, batch operations, and N+1 query prevention.
Tool: references/query-performance.md [2/4] Description: Queue all deletions comments.forEach(comment => { batch.collection('comments').delete(comment.id); }); batch.collection('posts').delete(postId); await batch.send(); // Post and all comments deleted atomically } ``` **Batch operation limits:** - **Must be enabled first** in Dashboard > Settings > Application (disabled by default; returns 403 otherwise) - Operations execute in a single database transaction - All succeed or all rollback - Res
Tool: references/query-performance.md [3/4] Description: For database-level optimization, ensure proper indexes.
Tool: references/query-performance.md [4/4] Description: is >> number of records, you have N+1 } ``` **Prevention checklist:** - [ ] Always use `expand` for displaying related data - [ ] Never fetch related records in loops - [ ] Batch fetch when expand isn't available - [ ] Consider view collections for complex joins - [ ] Monitor request counts during development Reference: [PocketBase Expand](https://pocketbase.io/docs/api-records/#expand) ## 7.
Malicious tool definition detected
Tool: references/realtime.md [1/3] Description: # Realtime **Impact: MEDIUM** SSE subscriptions, event handling, connection management, and authentication with realtime.
Tool: references/realtime.md [2/3] Description: // If connection drops, UI shows stale data indefinitely // Assuming connection is always stable function PostList() { useEffect(() => { pb.collection('posts').subscribe('*', handleChange); }, []); // No awareness of connection state } ``` **Correct (robust connection handling):** ```javascript // Monitor connection state function useRealtimeConnection() { const [connected, setConnected] = useState(false); const [lastSync, setLastSync] = useState(n
Tool: references/realtime.md [3/3]
Malicious tool definition detected
Tool: references/sdk-usage.md [1/4] Description: # SDK Usage **Impact: HIGH** JavaScript SDK initialization, auth store patterns, error handling, request cancellation, and safe parameter binding.
Tool: references/sdk-usage.md [2/4] Description: async function createPost(data) { try { return await pb.collection('posts').create(data); } catch (error) { if (error instanceof ClientResponseError) { console.log('Status:', error.status); console.log('Response:', error.response); console.log('URL:', error.url); console.log('Is abort:', error.isAbort); // Handle specific status codes switch (error.status) { case 400: // Validation error - extract user-friendly messages only // IMPORTANT: Don't ex
Tool: references/sdk-usage.md [3/4] Description: **Correct (using pb.filter with parameters):** ```javascript // Safe parameter binding async function searchPosts(userInput) { const posts = await pb.collection('posts').getList(1, 20, { filter: pb.filter('title ~ {:search}', { search: userInput }) }); return posts; } // Multiple parameters async function filterPosts(status, authorId, minViews) { const posts = await pb.collection('posts').getList(1, 20, { filter: pb.filter( 'status = {:status} &&
Tool: references/sdk-usage.md [4/4]
Malicious tool definition detected
Tool: rules/_sections.md Description: # Section Definitions This file defines the rule categories for PocketBase best practices.
Malicious tool definition detected
Tool: rules/_template.md Description: --- title: Clear, Action-Oriented Title (e.g., "Use Cursor-Based Pagination for Large Lists") impact: MEDIUM impactDescription: Brief description of performance/security impact tags: relevant, comma-separated, tags --- ## [Rule Title] [1-2 sentence explanation of the problem and why it matters.
Malicious tool definition detected
Tool: rules/auth-impersonation.md Description: --- title: Use Impersonation for Admin Operations impact: MEDIUM impactDescription: Safe admin access to user data without password sharing tags: authentication, admin, impersonation, superuser --- ## Use Impersonation for Admin Operations Impersonation allows superusers to generate tokens for other users, enabling admin support tasks and API key functionality without sharing passwords.
Malicious tool definition detected
Tool: rules/auth-mfa.md Description: --- title: Implement Multi-Factor Authentication impact: HIGH impactDescription: Additional security layer for sensitive applications tags: authentication, mfa, security, 2fa, otp --- ## Implement Multi-Factor Authentication MFA requires users to authenticate with two different methods.
Malicious tool definition detected
Tool: rules/auth-oauth2.md Description: --- title: Integrate OAuth2 Providers Correctly impact: CRITICAL impactDescription: Secure third-party authentication with proper flow handling tags: authentication, oauth2, google, github, social-login --- ## Integrate OAuth2 Providers Correctly OAuth2 integration should use the all-in-one method for simplicity and security.
Malicious tool definition detected
Tool: rules/auth-password.md Description: --- title: Implement Secure Password Authentication impact: CRITICAL impactDescription: Secure user login with proper error handling and token management tags: authentication, password, login, security --- ## Implement Secure Password Authentication Password authentication should include proper error handling, avoid exposing whether emails exist, and correctly manage the auth store.
Malicious tool definition detected
Tool: rules/auth-token-management.md Description: --- title: Manage Auth Tokens Properly impact: CRITICAL impactDescription: Prevents unauthorized access, handles token expiration gracefully tags: authentication, tokens, refresh, security, session --- ## Manage Auth Tokens Properly Auth tokens should be refreshed before expiration, validated on critical operations, and properly cleared on logout.
Malicious tool definition detected
Tool: rules/coll-auth-vs-base.md Description: --- title: Use Auth Collections for User Accounts impact: CRITICAL impactDescription: Built-in authentication, password hashing, OAuth2 support tags: collections, auth, users, authentication, design --- ## Use Auth Collections for User Accounts Auth collections provide built-in authentication features including secure password hashing, email verification, OAuth2 support, and token management.
Malicious tool definition detected
Tool: rules/coll-field-types.md Description: --- title: Choose Appropriate Field Types for Your Data impact: CRITICAL impactDescription: Prevents data corruption, improves query performance, reduces storage tags: collections, schema, field-types, design --- ## Choose Appropriate Field Types for Your Data Selecting the wrong field type leads to data validation issues, wasted storage, and poor query performance.
Malicious tool definition detected
Tool: rules/coll-geopoint.md Description: --- title: Use GeoPoint Fields for Location Data impact: MEDIUM impactDescription: Built-in geographic queries, distance calculations tags: collections, geopoint, location, geographic, maps --- ## Use GeoPoint Fields for Location Data PocketBase provides a dedicated GeoPoint field type for storing geographic coordinates with built-in distance query support via `geoDistance()`.
Malicious tool definition detected
Tool: rules/coll-indexes.md Description: --- title: Create Indexes for Frequently Filtered Fields impact: CRITICAL impactDescription: 10-100x faster queries on large collections tags: collections, indexes, performance, query-optimization --- ## Create Indexes for Frequently Filtered Fields PocketBase uses SQLite which benefits significantly from proper indexing.
Malicious tool definition detected
Tool: rules/coll-relations.md Description: --- title: Configure Relations with Proper Cascade Options impact: CRITICAL impactDescription: Maintains referential integrity, prevents orphaned records, controls deletion behavior tags: collections, relations, foreign-keys, cascade, design --- ## Configure Relations with Proper Cascade Options Relation fields connect collections together.
Malicious tool definition detected
Tool: rules/coll-view-collections.md Description: --- title: Use View Collections for Complex Read-Only Queries impact: HIGH impactDescription: Simplifies complex queries, improves maintainability, enables aggregations tags: collections, views, sql, aggregation, design --- ## Use View Collections for Complex Read-Only Queries View collections execute custom SQL queries and expose results through the standard API.
Malicious tool definition detected
Tool: rules/deploy-backup.md Description: --- title: Implement Proper Backup Strategies impact: LOW-MEDIUM impactDescription: Prevents data loss, enables disaster recovery tags: production, backup, disaster-recovery, data-protection --- ## Implement Proper Backup Strategies Regular backups are essential for production deployments.
Malicious tool definition detected
Tool: rules/deploy-configuration.md Description: --- title: Configure Production Settings Properly impact: LOW-MEDIUM impactDescription: Secure and optimized production environment tags: production, configuration, security, environment --- ## Configure Production Settings Properly Production deployments require proper configuration of URLs, secrets, SMTP, and security settings.
Malicious tool definition detected
Tool: rules/deploy-rate-limiting.md Description: --- title: Enable Rate Limiting for API Protection impact: MEDIUM impactDescription: Prevents abuse, brute-force attacks, and DoS tags: production, security, rate-limiting, abuse-prevention --- ## Enable Rate Limiting for API Protection PocketBase v0.23+ includes built-in rate limiting.
Malicious tool definition detected
Tool: rules/deploy-reverse-proxy.md Description: --- title: Configure Reverse Proxy Correctly impact: LOW-MEDIUM impactDescription: HTTPS, caching, rate limiting, and security headers tags: production, nginx, caddy, https, proxy --- ## Configure Reverse Proxy Correctly Use a reverse proxy (Nginx, Caddy) for HTTPS termination, caching, rate limiting, and security headers.
Malicious tool definition detected
Tool: rules/deploy-sqlite-considerations.md Description: --- title: Optimize SQLite for Production impact: LOW-MEDIUM impactDescription: Better performance and reliability for SQLite database tags: production, sqlite, database, performance --- ## Optimize SQLite for Production PocketBase uses SQLite with optimized defaults.
Malicious tool definition detected
Tool: rules/file-serving.md Description: --- title: Generate File URLs Correctly impact: MEDIUM impactDescription: Proper URLs with thumbnails and access control tags: files, urls, thumbnails, serving --- ## Generate File URLs Correctly Use the SDK's `getURL` method to generate proper file URLs with thumbnail support and access tokens for protected files.
Malicious tool definition detected
Tool: rules/file-upload.md Description: --- title: Upload Files Correctly impact: MEDIUM impactDescription: Reliable uploads with progress tracking and validation tags: files, upload, storage, attachments --- ## Upload Files Correctly File uploads can use plain objects or FormData.
Malicious tool definition detected
Tool: rules/file-validation.md Description: --- title: Validate File Uploads impact: MEDIUM impactDescription: Prevents invalid uploads, improves security and UX tags: files, validation, security, upload --- ## Validate File Uploads Validate files on both client and server side.
Malicious tool definition detected
Tool: rules/query-back-relations.md Description: --- title: Use Back-Relations for Inverse Lookups impact: HIGH impactDescription: Fetch related records without separate queries tags: query, relations, back-relations, expand, inverse --- ## Use Back-Relations for Inverse Lookups Back-relations allow you to expand records that reference the current record, enabling inverse lookups in a single request.
Malicious tool definition detected
Tool: rules/query-batch-operations.md Description: --- title: Use Batch Operations for Multiple Writes impact: HIGH impactDescription: Atomic transactions, 10x fewer API calls, consistent state tags: query, batch, transactions, performance --- ## Use Batch Operations for Multiple Writes Batch operations combine multiple create/update/delete operations into a single atomic transaction.
Malicious tool definition detected
Tool: rules/query-expand.md Description: --- title: Expand Relations Efficiently impact: HIGH impactDescription: Eliminates N+1 queries, reduces API calls by 90%+ tags: query, relations, expand, joins, performance --- ## Expand Relations Efficiently Use the `expand` parameter to fetch related records in a single request.
Malicious tool definition detected
Tool: rules/query-field-selection.md Description: --- title: Select Only Required Fields impact: MEDIUM impactDescription: Reduces payload size, improves response time tags: query, fields, performance, bandwidth --- ## Select Only Required Fields Use the `fields` parameter to request only the data you need.
Malicious tool definition detected
Tool: rules/query-first-item.md Description: --- title: Use getFirstListItem for Single Record Lookups impact: MEDIUM impactDescription: Cleaner code, automatic error handling for not found tags: query, lookup, find, getFirstListItem --- ## Use getFirstListItem for Single Record Lookups Use `getFirstListItem()` when you need to find a single record by a field value other than ID.
Malicious tool definition detected
Tool: rules/query-n-plus-one.md Description: --- title: Prevent N+1 Query Problems impact: HIGH impactDescription: Reduces API calls from N+1 to 1-2, dramatically faster page loads tags: query, performance, n-plus-one, optimization --- ## Prevent N+1 Query Problems N+1 queries occur when you fetch a list of records, then make additional requests for each record's related data.
Malicious tool definition detected
Tool: rules/query-pagination.md Description: --- title: Use Efficient Pagination Strategies impact: HIGH impactDescription: 10-100x faster list queries on large collections tags: query, pagination, performance, lists --- ## Use Efficient Pagination Strategies Pagination impacts performance significantly.
Malicious tool definition detected
Tool: rules/realtime-auth.md Description: --- title: Authenticate Realtime Connections impact: MEDIUM impactDescription: Secure subscriptions respecting API rules tags: realtime, authentication, security, subscriptions --- ## Authenticate Realtime Connections Realtime subscriptions respect collection API rules.
Malicious tool definition detected
Tool: rules/realtime-events.md Description: --- title: Handle Realtime Events Properly impact: MEDIUM impactDescription: Consistent UI state, proper optimistic updates tags: realtime, events, state-management, ui --- ## Handle Realtime Events Properly Realtime events should update local state correctly, handle edge cases, and maintain UI consistency.
Malicious tool definition detected
Tool: rules/realtime-reconnection.md Description: --- title: Handle Realtime Connection Issues impact: MEDIUM impactDescription: Reliable realtime even with network interruptions tags: realtime, reconnection, resilience, offline --- ## Handle Realtime Connection Issues Realtime connections can disconnect due to network issues or server restarts.
Malicious tool definition detected
Tool: rules/realtime-subscribe.md Description: --- title: Implement Realtime Subscriptions Correctly impact: MEDIUM impactDescription: Live updates without polling, reduced server load tags: realtime, subscriptions, sse, websocket --- ## Implement Realtime Subscriptions Correctly PocketBase uses Server-Sent Events (SSE) for realtime updates.
Malicious tool definition detected
Tool: rules/rules-basics.md Description: --- title: Understand API Rule Types and Defaults impact: CRITICAL impactDescription: Prevents unauthorized access, data leaks, and security vulnerabilities tags: api-rules, security, access-control, authorization --- ## Understand API Rule Types and Defaults PocketBase uses five collection-level rules to control access.
Malicious tool definition detected
Tool: rules/rules-cross-collection.md Description: --- title: Use @collection for Cross-Collection Lookups impact: HIGH impactDescription: Enables complex authorization without denormalization tags: api-rules, security, cross-collection, relations --- ## Use @collection for Cross-Collection Lookups The `@collection` reference allows rules to query other collections, enabling complex authorization patterns like role-based access, team membership, and resource permissions.
Malicious tool definition detected
Tool: rules/rules-filter-syntax.md Description: --- title: Master Filter Expression Syntax impact: CRITICAL impactDescription: Enables complex access control and efficient querying tags: api-rules, filters, syntax, operators, security --- ## Master Filter Expression Syntax PocketBase filter expressions use a specific syntax for both API rules and client-side queries.
Malicious tool definition detected
Tool: rules/rules-locked-vs-open.md Description: --- title: Default to Locked Rules, Open Explicitly impact: CRITICAL impactDescription: Defense in depth, prevents accidental data exposure tags: api-rules, security, defaults, best-practices --- ## Default to Locked Rules, Open Explicitly New collections should start with locked (null) rules and explicitly open only what's needed.
Malicious tool definition detected
Tool: rules/rules-request-context.md Description: --- title: Use @request Context in API Rules impact: CRITICAL impactDescription: Enables dynamic, user-aware access control tags: api-rules, security, request-context, authentication --- ## Use @request Context in API Rules The `@request` object provides access to the current request context including authenticated user, request body, query parameters, and headers.
Malicious tool definition detected
Tool: rules/sdk-auth-store.md Description: --- title: Use Appropriate Auth Store for Your Platform impact: HIGH impactDescription: Proper auth persistence across sessions and page reloads tags: sdk, auth-store, persistence, storage --- ## Use Appropriate Auth Store for Your Platform The auth store persists authentication state.
Malicious tool definition detected
Tool: rules/sdk-auto-cancellation.md Description: --- title: Understand and Control Auto-Cancellation impact: MEDIUM impactDescription: Prevents race conditions, improves UX for search/typeahead tags: sdk, cancellation, requests, performance --- ## Understand and Control Auto-Cancellation The SDK automatically cancels duplicate pending requests.
Malicious tool definition detected
Tool: rules/sdk-error-handling.md Description: --- title: Handle SDK Errors Properly impact: HIGH impactDescription: Graceful error recovery, better UX, easier debugging tags: sdk, errors, error-handling, exceptions --- ## Handle SDK Errors Properly All SDK methods return Promises that may reject with `ClientResponseError`.
Malicious tool definition detected
Tool: rules/sdk-field-modifiers.md Description: --- title: Use Field Modifiers for Incremental Updates impact: HIGH impactDescription: Atomic updates, prevents race conditions, cleaner code tags: sdk, modifiers, relations, files, numbers, atomic --- ## Use Field Modifiers for Incremental Updates PocketBase supports `+` and `-` modifiers for incrementing numbers, appending/removing relation IDs, and managing file arrays without replacing the entire value.
Malicious tool definition detected
Tool: rules/sdk-filter-binding.md Description: --- title: Use Safe Parameter Binding in Filters impact: CRITICAL impactDescription: Prevents injection attacks, handles special characters correctly tags: sdk, filters, security, injection, parameters --- ## Use Safe Parameter Binding in Filters Always use `pb.filter()` with parameter binding when constructing filters with user input.
Malicious tool definition detected
Tool: rules/sdk-initialization.md Description: --- title: Initialize PocketBase Client Correctly impact: HIGH impactDescription: Proper setup enables auth persistence, SSR support, and optimal performance tags: sdk, initialization, client, setup --- ## Initialize PocketBase Client Correctly Client initialization should consider the environment (browser, Node.js, SSR), auth store persistence, and any required polyfills.
Malicious tool definition detected
Tool: rules/sdk-send-hooks.md Description: --- title: Use Send Hooks for Request Customization impact: MEDIUM impactDescription: Custom headers, logging, response transformation tags: sdk, hooks, middleware, headers, logging --- ## Use Send Hooks for Request Customization The SDK provides `beforeSend` and `afterSend` hooks for intercepting and modifying requests and responses globally.