{
    "version": "https://jsonfeed.org/version/1",
    "title": "Dibakar Mitra - Software Developer Portfolio",
    "home_page_url": "https://www.dibakarmitra.com/",
    "feed_url": "https://www.dibakarmitra.com/api/feed/feed.json",
    "description": "Professional portfolio of Dibakar Mitra, a skilled Backend Developer specializing in Laravel, Django, and API development. Crafting efficient and scalable server-side solutions for complex web applications.",
    "items": [
        {
            "id": "https://www.dibakarmitra.com/notes/activity-scope",
            "content_html": "\n# Activity Scope: Laravel Audit Trail Package\n\nLooking for a powerful activity logging system for your Laravel applications? Meet Activity Scope - a comprehensive audit trail package that combines performance, privacy, and developer experience.\n\n## Why Activity Scope?\n\nIn modern Laravel development, tracking user actions and maintaining audit trails is essential. Most existing solutions either:\n\n- Are overly complex with steep learning curves\n- Sacrifice performance for features  \n- Ignore privacy concerns in modern applications\n- Force rigid logging patterns\n\nActivity Scope changes this with a thoughtful approach that prioritizes what developers actually need.\n\n## Key Features\n\n### Fluent Builder API\n\n```php\nactivity()\n    ->on($post)\n    ->did('published')\n    ->with(['scheduled_at' => now()])\n    ->success()\n    ->log();\n```\n\nClean, readable, and chainable API that makes sense.\n\n### Smart Actor Resolution\n\n```php\n// Automatically uses auth()->user()\nactivity()->created($post)->log();\n\n// Override when needed\nactivity()->by($admin)->on($user)->did('suspended')->log();\n```\n\nWorks the way you expect, with sensible defaults.\n\n### Privacy-First Design\n\n```php\nactivity()\n    ->sensitive()\n    ->with(['api_key' => 'sk_live_123456']) // Auto-redacted\n    ->log();\n```\n\nBuilt-in IP anonymization, sensitive data scrubbing, and privacy controls.\n\n### Modular Traits\n\n```php\n// Automatic logging\nclass Post extends Model {\n    use LogsActivity;\n}\n\n// Manual control\nclass User extends Model {\n    use HasActivities;\n    \n    function login() {\n        $this->newActivity()->did('logged_in')->log();\n    }\n}\n```\n\nUse what you need, ignore what you don't.\n\n## Getting Started\n\n### Installation\n\n```bash\ncomposer require dibakar/activity-scope\nphp artisan activityscope:install\nphp artisan migrate\n```\n\n### Your First Activity Log\n\n```php\n// That's it. You're ready.\nactivity()\n    ->on($user)\n    ->did('registered')\n    ->log();\n```\n\n## Real-World Use Cases\n\n### E-commerce Order Tracking\n\n```php\nclass OrderService {\n    public function processOrder(Order $order, User $user) {\n        activity()\n            ->by($user)\n            ->created($order)\n            ->with(['total' => $order->total, 'items' => $order->items->count()])\n            ->tags(['order', 'ecommerce'])\n            ->log();\n            \n        if ($payment->successful) {\n            activity()\n                ->by($user)\n                ->on($order)\n                ->did('payment_confirmed')\n                ->success()\n                ->log();\n        }\n    }\n}\n```\n\n### Security Event Logging\n\n```php\n// Failed login attempts\nactivity()\n    ->byGuest()\n    ->on($user)\n    ->failed('Invalid credentials')\n    ->severity('warning')\n    ->tags(['auth', 'security'])\n    ->log();\n\n// Admin actions\nactivity()\n    ->by($admin)\n    ->on($user)\n    ->did('account_suspended')\n    ->severity('critical')\n    ->tags(['admin', 'security'])\n    ->log();\n```\n\n### Analytics Integration\n\n```php\n// Track user engagement\nactivity()\n    ->by($user)\n    ->on($article)\n    ->did('viewed')\n    ->with(['duration' => $readingTime, 'source' => 'search'])\n    ->tags(['analytics', 'engagement'])\n    ->log();\n```\n\n## Advanced Features\n\n### Human-Readable Messages\n\n```php\n$activity = Activity::first();\necho $activity->message(); \n// \"John Doe published Post 'Getting Started with Laravel' 2 minutes ago\"\n```\n\n### Powerful Query Scopes\n\n```php\n// Find all admin actions in last week\n$adminActions = Activity::by($admin)\n    ->where('created_at', '>=', now()->subDays(7))\n    ->where('severity', 'critical')\n    ->get();\n\n// Security events\n$securityEvents = Activity::withTag('security')\n    ->failed()\n    ->get();\n```\n\n### Performance Optimized\n\n- Efficient Queries: Optimized database interactions\n- Queue Support: Async logging when you need it\n- Smart Pruning: Automatic cleanup of old logs\n- Minimal Overhead: Won't slow down your application\n\n## Security & Compliance\n\n### GDPR Compliant\n\n```php\n// Automatic privacy controls\n'privacy' => [\n    'sanitize_data' => true,\n    'anonymize_ip' => true,\n    'sensitive_fields' => [\n        'password', 'token', 'api_key', 'credit_card', 'ssn'\n    ],\n],\n```\n\n### Audit Trail Standards\n\n- Immutable logs (once written, never changed)\n- Complete context (who, what, when, where)\n- Tamper-evident (cryptographic hashes available)\n- Searchable and filterable\n\n## Developer Experience\n\n### Clean Configuration\n\n```php\n// Simple, sensible defaults\nreturn [\n    'enabled' => env('ACTIVITY_LOGGER_ENABLED', true),\n    'auto_log' => env('ACTIVITY_LOGGER_AUTO_LOG', false),\n    'privacy' => [\n        'sanitize_data' => true,\n        'track_ip_address' => true,\n        'anonymize_ip' => false,\n    ],\n];\n```\n\n### Comprehensive Testing\n\n```php\n// Built-in test helpers\n$this->assertActivityLogged('created', $post);\n$this->assertDatabaseHas('activities', [\n    'action' => 'published',\n    'subject_id' => $post->id\n]);\n```\n\n## Why Choose Activity Scope?\n\n1. **Purpose-Built**: Designed specifically for Laravel's ecosystem\n2. **Privacy-First**: Security and compliance built-in\n3. **Performance**: Won't slow down your application\n4. **Flexible**: Use what you need, ignore what you don't\n5. **Intuitive**: API that just makes sense\n6. **Production-Ready**: Battle-tested in real applications\n\n## Resources\n\n- **Documentation**: [Complete API Reference](https://github.com/dibakarmitra/activity-scope/blob/main/API.md)\n- **GitHub**: [Repository & Issues](https://github.com/dibakarmitra/activity-scope)\n- **Packagist**: [Install via Composer](https://packagist.org/packages/dibakar/activity-scope)\n- **Examples**: [Real-world code samples](https://github.com/dibakarmitra/activity-scope/tree/main/examples)\n\n## Get Started Today\n\nStop fighting with complex logging solutions. Activity Scope gives you the power, flexibility, and privacy features you need.\n\n```bash\ncomposer require dibakar/activity-scope\n```\n\nYour future self will thank you for choosing a logging solution that actually respects your time and your users' privacy.\n\n---\n\n**Hot Tip**: Check out the [examples directory](https://github.com/dibakarmitra/activity-scope/tree/main/examples) for ready-to-use implementations for common scenarios like e-commerce, user management, and security monitoring.\n\n---\n\n#Laravel #PHP #AuditTrail #ActivityLogging #OpenSource #DeveloperTools\n",
            "url": "https://www.dibakarmitra.com/notes/activity-scope",
            "title": " Activity Scope: Laravel Audit Trail Package",
            "date_modified": "2025-12-20T00:00:00.000Z",
            "author": {
                "name": "Dibakar Mitra",
                "url": "https://www.dibakarmitra.com"
            },
            "tags": [
                "Laravel",
                "PHP",
                "Audit Trails",
                "Activity Logging",
                "Laravel Package"
            ]
        },
        {
            "id": "https://www.dibakarmitra.com/notes/config-ship-package",
            "content_html": "\n# Config-Ship: Simple and Safe Configuration Management\n\nConfig-Ship is a lightweight npm package designed for Node.js applications that need a simple yet powerful way to manage configurations with support for layered defaults, environment variables, and runtime overrides.\n\n## Key Features\n\n- **Layered Configuration**: Combine defaults, environment variables, and runtime overrides\n- **Package-Safe**: Designed to work well in both ESM and CommonJS modules\n- **Minimal Dependencies**: Lightweight with minimal external dependencies\n- **TypeScript Support**: Built with TypeScript for better developer experience\n- **Runtime Access**: Get and set configuration values at runtime\n\n## Installation\n\nInstall Config-Ship using your preferred package manager:\n\n```bash\n# Using npm\nnpm install config-ship\n\n# Using yarn\nyarn add config-ship\n\n# Using pnpm\npnpm add config-ship\n```\n\n## Basic Usage\n\n### 1. Create a Configuration File\n\nCreate a configuration file (e.g., `app.config.ts`):\n\n```typescript\n// app.config.ts\nexport default {\n  app: {\n    name: \"MyApp\",\n    version: \"1.0.0\"\n  },\n  server: {\n    host: \"localhost\",\n    port: 3000,\n    environment: process.env.NODE_ENV || \"development\"\n  },\n  features: {\n    darkMode: true,\n    notifications: true\n  }\n};\n```\n\n### 2. Use the Configuration in Your Application\n\n```typescript\n// app.ts\nimport { createConfig } from 'config-ship';\nimport config from './app.config.js';\n\n// Initialize the configuration\nconst appConfig = createConfig({\n  defaults: config,\n  envPrefix: 'APP_',  // Optional: prefix for environment variables\n  envFile: '.env'     // Optional: path to .env file\n});\n\n// Access configuration values\nconsole.log(`Starting ${appConfig.get('app.name')} v${appConfig.get('app.version')}`);\nconsole.log(`Server running at http://${appConfig.get('server.host')}:${appConfig.get('server.port')}`);\n\n// Check feature flags\nif (appConfig.get('features.darkMode')) {\n  console.log('Dark mode is enabled');\n}\n```\n\n## Environment Variables\n\nConfig-Ship can load environment variables from a `.env` file or `process.env`. By default, it looks for a `.env` file in your project root.\n\nExample `.env` file:\n```env\nAPP_SERVER_PORT=4000\nAPP_FEATURES_DARKMODE=false\n```\n\nEnvironment variables should be prefixed (default is no prefix) and use `_` for nested properties. For example, `server.port` becomes `SERVER_PORT` or `APP_SERVER_PORT` if prefix is set to `APP_`.\n\n## Runtime Configuration\n\nYou can modify configuration values at runtime:\n\n```typescript\n// Set a configuration value at runtime\nappConfig.set('server.port', 4000);\n\n// Check if a configuration key exists\nif (appConfig.has('features.notifications')) {\n  console.log('Notifications feature exists');\n}\n\n// Get all configuration\nconst allConfig = appConfig.all();\nconsole.log('Full configuration:', allConfig);\n```\n\n## TypeScript Support\n\nConfig-Ship is written in TypeScript and provides excellent type support:\n\n```typescript\n// types.ts\ninterface AppConfig {\n  app: {\n    name: string;\n    version: string;\n  };\n  server: {\n    host: string;\n    port: number;\n    environment: 'development' | 'production' | 'test';\n  };\n  features: {\n    darkMode: boolean;\n    notifications: boolean;\n  };\n}\n\n// app.ts\nimport { createConfig } from 'config-ship';\nimport config from './app.config.js';\n\nconst appConfig = createConfig<AppConfig>({\n  defaults: config\n});\n\n// Type-safe access\nconst port: number = appConfig.get('server.port');\n```\n\n## Best Practices\n\n1. **Keep Sensitive Data Secure**: Use environment variables for secrets and sensitive information.\n2. **Use TypeScript**: Take advantage of TypeScript for better type safety and autocompletion.\n3. **Document Configuration**: Document available configuration options and their purposes.\n4. **Environment-Specific Configs**: Use environment variables to adjust configuration between different environments.\n5. **Validate Early**: Validate configuration on application startup to catch issues early.\n\n## API Reference\n\n### `createConfig(options)`: ConfigInstance\n\nCreates a new configuration instance.\n\n**Options:**\n- `defaults`: Object containing default configuration values\n- `envPrefix`: Prefix for environment variables (default: '')\n- `envFile`: Path to .env file (default: '.env')\n- `rootFile`: Path to root directory for resolving relative paths (default: process.cwd())\n\n**Returns:**\n- `get(key: string): any` - Get a configuration value by dot notation\n- `set(key: string, value: any): void` - Set a configuration value\n- `has(key: string): boolean` - Check if a configuration key exists\n- `all(): object` - Get all configuration values\n\n## Best Practices\n\n1. **Keep Sensitive Data Secure**: Never commit sensitive information directly in your configuration files. Use environment variables for secrets.\n2. **Use Environment-Specific Configs**: Take advantage of environment-specific overrides to manage different deployment environments.\n3. **Validate Early**: Add validation to catch configuration errors as early as possible.\n4. **Document Your Configuration**: Maintain clear documentation for all configuration options and their purposes.\n\n## Conclusion\n\nConfig-Ship provides a clean and maintainable way to manage configurations in your JavaScript applications. With its support for environment variables, validation, and TypeScript, it's an excellent choice for projects of any size.\n\nFor more advanced usage and API documentation, check out the [official GitHub repository](https://github.com/dibakarmitra/config-ship).\n\n## License\n\nThis project is open-source and available under the MIT License.\n",
            "url": "https://www.dibakarmitra.com/notes/config-ship-package",
            "title": "Config-Ship: Lightweight Configuration Resolver for Node.js",
            "summary": "A lightweight, package-safe configuration resolver with layered defaults, env, and runtime overrides.",
            "date_modified": "2025-12-18T00:00:00.000Z",
            "author": {
                "name": "Dibakar Mitra",
                "url": "https://www.dibakarmitra.com"
            },
            "tags": [
                "javaScript",
                "configuration",
                "node.js",
                "typescript",
                "esm",
                "config"
            ]
        },
        {
            "id": "https://www.dibakarmitra.com/notes/laravel-dynamic-filters",
            "content_html": "\n# Laravel Dynamic Filters\n\nA robust and flexible filtering system for Laravel Eloquent models that makes building complex, dynamic queries a breeze. This package provides an elegant, fluent API for filtering, searching, and sorting your Eloquent models with minimal configuration.\n\n## ✨ Key Features\n\n- **Expressive Filtering**: Chainable methods and intuitive syntax for complex queries\n- **Advanced Search**: Full-text search with fuzzy matching and term normalization\n- **Relationship Support**: Filter across model relationships with nested conditions\n- **Type Safety**: Strict type checking and automatic value casting\n- **Performance Optimized**: Efficient query building with minimal overhead\n- **Security First**: Whitelisting and input validation out of the box\n- **Extensible**: Easy to create and register custom filters\n- **Modern PHP**: Built with PHP 8.1+ features and type hints\n\n## 🚀 Installation\n\n### Requirements\n- PHP 8.1 or higher\n- Laravel 10.x or later\n- Composer\n\n### Install via Composer\n```bash\ncomposer require dibakar/laravel-dynamic-filters\n```\n\n### Publish Configuration (Optional)\n```bash\nphp artisan vendor:publish --provider=\"Dibakar\\LaravelDynamicFilters\\DynamicFiltersServiceProvider\" --tag=\"config\"\n```\n\n## 🚀 Quick Start\n\n### 1. Prepare Your Model\n\nAdd the `HasDynamicFilter` trait to your Eloquent model and define the filterable, searchable, and sortable fields:\n\n```php\nuse Dibakar\\LaravelDynamicFilters\\Traits\\HasDynamicFilter;\nuse Illuminate\\Database\\Eloquent\\Model;\n\nclass Post extends Model\n{\n    use HasDynamicFilter;\n\n    /**\n     * Fields that can be searched.\n     */\n    protected $searchable = [\n        'title',\n        'content',\n        'author.name',       // Search in relationships\n        'tags.name'          // Search in many-to-many relationships\n    ];\n\n    /**\n     * Fields that can be filtered with operators.\n     */\n    protected $filterable = [\n        'id',\n        'status',\n        'category_id',\n        'published_at',\n        'views',\n        'is_featured',\n    ];\n\n    /**\n     * Fields that can be used for sorting.\n     */\n    protected $sortable = [\n        'created_at' => 'desc',  // Default sort\n        'title' => 'asc',\n        'views' => 'desc',\n    ];\n}\n```\n\n### 2. Basic Filtering\n\nFilter your models using query parameters in your controller:\n\n```php\n// GET /posts?status=published&created_at[gt]=2023-01-01&sort=-views,title\npublic function index(Request $request)\n{\n    $posts = Post::filter($request->query())\n        ->with(['author', 'category', 'tags']) // Eager load relationships\n        ->paginate($request->per_page ?? 15);\n\n    return response()->json($posts);\n}\n```\n\n### 3. Search Functionality\n\nSearch across searchable fields with a simple API:\n\n```php\n// GET /posts?q=laravel+framework\npublic function search(Request $request)\n{\n    $posts = Post::search($request->q)\n        ->filter($request->except('q')) // Apply additional filters\n        ->paginate($request->per_page ?? 15);\n\n    return response()->json($posts);\n}\n```\n\n### 4. Sorting Results\n\nSort your results using the `sort` parameter in your requests. The `-` prefix indicates descending order.\n\n```php\n// In your controller\n$posts = Post::sort($request->input('sort'))->get();\n\n// Or chain it with filters\n$posts = Post::filter($filters)\n    ->sort($request->input('sort', 'created_at,desc'))\n    ->paginate(15);\n```\n\nExample requests:\n```\nGET /posts?sort=title             // Sort by title (ascending)\nGET /posts?sort=title,asc         // Same as above (explicit ascending)\nGET /posts?sort=title,desc        // Sort by title (descending)\nGET /posts?sort=-title            // Alternative: Sort by title (descending)\nGET /posts?sort=views,desc&sort=title,asc  // Multiple sort fields\n```\n\n### 5. Pagination\n\nPagination works seamlessly with Laravel's built-in pagination:\n\n```php\n// GET /posts?page=2&per_page=20\n$posts = Post::filter($request->query())\n    ->paginate($request->per_page ?? 15);\n```\n\n## 🚀 Advanced Usage\n\n### Complex Filter Groups\n\nCreate complex filter conditions with AND/OR logic:\n\n```php\n// Example: (status = 'published' AND (title LIKE '%Laravel%' OR views > 100)) AND (author_id = 1 OR author_id = 2)\n$filters = [\n    '_group' => [\n        'boolean' => 'and',\n        'filters' => [\n            'status' => 'published',\n        ],\n        'nested' => [\n            [\n                'boolean' => 'or',\n                'filters' => [\n                    'title' => ['like' => '%Laravel%'],\n                    'views' => ['gt' => 100],\n                ],\n            ],\n            [\n                'boolean' => 'or',\n                'filters' => [\n                    'author_id' => [1, 2],\n                ],\n            ],\n        ],\n    ],\n];\n\n$posts = Post::filter($filters)->get();\n```\n\n### Custom Filter Classes\n\nFor complex filtering logic, create a custom filter class:\n\n```php\n<?php\n\nnamespace App\\Filters;\n\nuse Dibakar\\LaravelDynamicFilters\\Contracts\\FilterContract;\nuse Illuminate\\Database\\Eloquent\\Builder;\nuse Illuminate\\Support\\Carbon;\n\nclass PublishedInLastDaysFilter implements FilterContract\n{\n    public function apply(Builder $query, $value, string $property): Builder\n    {\n        $days = is_numeric($value) ? (int) $value : 7; // Default to 7 days if invalid\n        return $query->where('published_at', '>=', Carbon::now()->subDays($days));\n    }\n\n    public function validate($value): bool\n    {\n        return is_numeric($value) && $value > 0;\n    }\n\n    public function getValidationMessage(): string\n    {\n        return 'The days parameter must be a positive number.';\n    }\n}\n```\n\nRegister your custom filter in `config/dynamic-filters.php`:\n\n```php\n'custom_filters' => [\n    'published_in_days' => \\App\\Filters\\PublishedInLastDaysFilter::class,\n    // Add more custom filters as needed\n],\n```\n\nNow use it in your API:\n\n```\n// GET /posts?published_in_days=30\n$recentPosts = Post::filter(request()->query())->get();\n```\n\n## Available Operators\n\n| Operator | Description | Example |\n|----------|-------------|---------|\n| `=` | Equals | `?status=active` |\n| `neq` | Not equals | `?status[neq]=inactive` |\n| `gt` | Greater than | `?views[gt]=100` |\n| `gte` | Greater than or equal | `?rating[gte]=4` |\n| `lt` | Less than | `?price[lt]=100` |\n| `lte` | Less than or equal | `?age[lte]=30` |\n| `like` | Case-sensitive pattern matching | `?name[like]=%john%` |\n| `ilike` | Case-insensitive pattern matching | `?email[ilike]=%gmail.com` |\n| `in` | Value is in list | `?status[in]=active,pending` |\n| `not_in` | Value is not in list | `?id[not_in]=1,2,3` |\n| `between` | Value is between two values | `?created_at[between]=2023-01-01,2023-12-31` |\n| `null` | Field is null | `?deleted_at[null]` |\n| `notnull` | Field is not null | `?updated_at[notnull]` |\n\n## Performance Optimization\n\n### Database Indexing\n\n```php\n// In a migration\npublic function up()\n{\n    Schema::table('posts', function (Blueprint $table) {\n        // Single column indexes\n        $table->index('status');\n        $table->index('published_at');\n        $table->index('views');\n        \n        // Composite index for common filter combinations\n        $table->index(['status', 'published_at']);\n        $table->index(['category_id', 'status', 'published_at']);\n    });\n}\n```\n\n### Selective Field Loading\n\n```php\n// Only select the fields you need\n$posts = Post::select([\n        'id', 'title', 'slug', 'excerpt',\n        'status', 'published_at', 'author_id', 'category_id'\n    ])\n    ->with([\n        'author:id,name,avatar',\n        'category:id,name,slug',\n        'tags:id,name,slug'\n    ])\n    ->filter($filters)\n    ->paginate(15);\n```\n\n## Security\n\nBy default, only fields defined in the `$filterable` array can be filtered. This is a security measure to prevent unauthorized filtering on sensitive fields.\n\nYou can also define a global whitelist in the config file that applies to all models:\n\n```php\n'global_whitelist' => [\n    'id',\n    'status',\n    'created_at',\n    'updated_at',\n],\n```\n\n## Conclusion\n\nLaravel Dynamic Filters provides a powerful, flexible, and secure way to implement complex filtering in your Laravel applications. With its intuitive API and extensive feature set, you can quickly build robust filtering solutions that scale with your application's needs.\n\n## Resources\n\n- [GitHub Repository](https://github.com/dibakarmitra/laravel-dynamic-filters)\n- [Packagist](https://packagist.org/packages/dibakar/laravel-dynamic-filters)\n- [Issues](https://github.com/dibakarmitra/laravel-dynamic-filters/issues)\n\n## License\n\nThe MIT License (MIT). Please see [License File](https://github.com/dibakarmitra/laravel-dynamic-filters/blob/main/LICENSE.md) for more information.\n",
            "url": "https://www.dibakarmitra.com/notes/laravel-dynamic-filters",
            "title": "Laravel Dynamic Filters: A Comprehensive Guide to Flexible Query Building",
            "summary": "Learn how to implement powerful, flexible filtering in your Laravel applications with the Laravel Dynamic Filters package.",
            "date_modified": "2025-09-18T00:00:00.000Z",
            "author": {
                "name": "Dibakar Mitra",
                "url": "https://www.dibakarmitra.com"
            },
            "tags": [
                "laravel",
                "php",
                "query-builder",
                "api",
                "filters"
            ]
        },
        {
            "id": "https://www.dibakarmitra.com/notes/laravel-ownership",
            "content_html": "\n# Laravel Ownership Package – Simplify Model Ownership in Laravel\n\nManaging ownership relationships between models can get tricky in Laravel projects. The **[Laravel Ownership package](https://github.com/dibakarmitra/laravel-ownership)** by Dibakar Mitra makes it simple and elegant.\n\n## 🚀 What is Laravel Ownership?\nThis package allows you to assign and manage ownership between different models. For example, a `User` can own a `Project`, `Team`, or any other entity. It uses a clean polymorphic approach without repeating boilerplate code.\n\n## ✨ Features\n- Polymorphic ownership handling out of the box.  \n- Easy to integrate with existing models.  \n- Supports roles for more advanced ownership structures.  \n- Database migration included (`ownerships` table).  \n- Works seamlessly with **Laravel 9, 10, and 11**.  \n\n## 📦 Installation\n\n1. Require the package:\n   ```bash\n   composer require dibakar/laravel-ownership\n   ```\n\n   *(if you’re testing the dev branch, use `composer require dibakar/laravel-ownership:dev-main`)*\n\n2. Publish and run the migration:\n   ```bash\n   php artisan vendor:publish --tag=ownership-migrations\n   php artisan migrate\n   ```\n\n3. Add the `HasOwnership` trait to your models:\n   ```php\n   use Dibakar\\Ownership\\Traits\\HasOwnership;\n\n   class Project extends Model\n   {\n       use HasOwnership;\n   }\n   ```\n\n## 🔧 Usage Example\n```php\n$project = Project::find(1);\n$user = User::find(1);\n\n// Assign ownership\n$project->addOwner($user, 'manager');\n\n// Check ownership\nif ($project->isOwnedBy($user)) {\n    echo \"User owns this project!\";\n}\n```\n\n## 🤝 Why Use This Package?\n- Keeps your code clean and DRY.  \n- Avoids writing repetitive relationship logic.  \n- Flexible enough to handle **teams, clients, vendors, or multi-role ownership**.  \n\n## 📚 Resources\n- [GitHub Repository](https://github.com/dibakarmitra/laravel-ownership)  \n- [Packagist Package](https://packagist.org/packages/dibakar/laravel-ownership)  \n\n## License\nThis package is open-source and available under the MIT License.\n\nMake ownership handling in Laravel easy and maintainable with **dibakar/laravel-ownership**. 🚀\n",
            "url": "https://www.dibakarmitra.com/notes/laravel-ownership",
            "title": "Laravel Ownership Package – Simplify Model Ownership in Laravel",
            "date_modified": "2025-09-05T00:00:00.000Z",
            "author": {
                "name": "Dibakar Mitra",
                "url": "https://www.dibakarmitra.com"
            },
            "tags": [
                "Laravel",
                "PHP",
                "Package",
                "Ownership",
                "Eloquent"
            ]
        },
        {
            "id": "https://www.dibakarmitra.com/notes/laravel-api-response-system",
            "content_html": "\n# How to Build a Clean and Consistent Laravel API Response System\n\nWhen building APIs in Laravel, one of the most important principles is consistency. Clients should always get predictable, structured responses—whether things go right or wrong. In this tutorial, we’ll walk through how to build a reusable API response system and use it in a `bulkDelete` endpoint example.\n\n## Step 1: Create a Base Controller for API Responses\n\nLet’s start with a custom base controller that all your other controllers can extend. This controller provides a consistent structure for success and error responses.\n\n### Key Features:\n\n- Unified format for JSON responses\n- Optional data encryption\n- Standard HTTP status messages\n- Pagination support\n\n```php\nclass Controller extends BaseController\n{\n    use AuthorizesRequests, DispatchesJobs, ValidatesRequests;\n\n    protected $errorMessages = [ /* HTTP status messages */ ];\n\n    protected function isEncryptionEnabled(): bool\n    {\n        return false; // Toggle encryption here\n    }\n\n    protected function getRequestData($request): array\n    {\n        if ($this->isEncryptionEnabled()) {\n            $decrypted = app('securityService')->decrypt($request->input, $request->version ?? false);\n            return json_decode($decrypted, true) ?? [];\n        }\n\n        return $request->all();\n    }\n\n    protected function sendSuccess($data = null, $message = null, int $status = 200): JsonResponse\n    {\n        return $this->sendResponse('success', $status, $message, $data);\n    }\n\n    protected function sendError($message = null, int $status = 400): JsonResponse\n    {\n        if (!isset($this->errorMessages[$status])) $status = 400;\n        return $this->sendResponse('error', $status, $message);\n    }\n\n    protected function validationError($message, $response = null): JsonResponse\n    {\n        return $this->sendResponse('error', 422, $message, $response);\n    }\n\n    protected function sendResponse(string $status, int $statusCode, $message = null, $data = null): JsonResponse\n    {\n        $statusMessage = $this->errorMessages[$statusCode] ?? 'Unknown Status';\n        $framed = $this->frameResponse($status, $statusCode, $statusMessage, $message, $this->prepareResponseData($data));\n        return response()->json($framed, $statusCode);\n    }\n\n    protected function frameResponse(string $status, int $statusCode, string $statusMessage, $message = null, $data = null): array\n    {\n        if ($data instanceof LengthAwarePaginator) {\n            $data = $this->formatPaginatedResponse($data);\n        }\n\n        return compact('status', 'statusCode', 'statusMessage', 'message', 'data');\n    }\n\n    protected function prepareResponseData($data)\n    {\n        return $this->isEncryptionEnabled() ? app('securityService')->encrypt(json_encode($data)) : $data;\n    }\n\n    protected function formatPaginatedResponse($paginator, bool $showLinks = false): array\n    {\n        $items = $paginator->items();\n\n        $response = [\n            'current_page' => (int)$paginator->currentPage(),\n            'items' => $items,\n            'last_page' => (int)$paginator->lastPage(),\n            'per_page' => (int)$paginator->perPage(),\n            'from' => (int)$paginator->firstItem(),\n            'to' => (int)$paginator->lastItem(),\n            'total' => (int)$paginator->total(),\n        ];\n\n        if ($showLinks) {\n            $response['next_page_url'] = $paginator->nextPageUrl();\n            $response['prev_page_url'] = $paginator->previousPageUrl();\n        }\n\n        return $response;\n    }\n}\n```\n\n## Step 2: Add a Bulk Delete API Endpoint\n\nWith the base response methods in place, implementing consistent endpoints becomes easy.\n\nHere’s an example `bulkDelete` method that validates input, checks authorization, and uses the unified response system.\n\n```php\npublic function bulkDelete(Request $request)\n{\n    $validator = Validator::make($request->all(), [\n        'ids' => 'required|array',\n        'ids.*' => 'exists:invoices,id',\n    ]);\n\n    if ($validator->fails()) {\n        return $this->validationError($validator->errors());\n    }\n\n    try {\n        $unauthorized = Invoice::whereIn('id', $request->ids)\n            ->where('user_id', '!=', backpack_user()->id)\n            ->exists();\n\n        if ($unauthorized) {\n            return $this->sendError('Unauthorized action.', 403);\n        }\n\n        $deletedCount = $this->invoiceService->bulkDelete($request->ids);\n\n        return $this->sendSuccess([], \"{$deletedCount} invoices deleted.\");\n    } catch (Exception $e) {\n        recordError('Failed to delete invoices', $e);\n        return $this->sendError('Failed to delete invoices.', 500);\n    }\n}\n```\n\n## Benefits of This Approach\n\n- **Clarity:** Your API always responds in the same JSON format.\n- **Maintainability:** Changes to the response structure happen in one place.\n- **Security:** Easily toggle request/response encryption if needed.\n- **Professionalism:** Clients and frontend developers will appreciate the consistency.\n\n## Conclusion\n\nA custom base controller for API responses in Laravel is a small investment that pays off in cleaner, more reliable code. It reduces repetition and ensures your APIs are easier to consume and debug.\n\nNeed help expanding this with authentication, filtering, or pagination features? Just ask.\n",
            "url": "https://www.dibakarmitra.com/notes/laravel-api-response-system",
            "title": "Building a Clean and Consistent Laravel API Response System",
            "date_modified": "2025-05-02T00:00:00.000Z",
            "author": {
                "name": "Dibakar Mitra",
                "url": "https://www.dibakarmitra.com"
            },
            "tags": [
                "Laravel",
                "PHP",
                "API Development",
                "Backend",
                "Web Security"
            ]
        },
        {
            "id": "https://www.dibakarmitra.com/notes/laravel12",
            "content_html": "\n# Laravel 12 – What's New & How to Get Started\n\nLaravel 12 is here! This release focuses on making development even smoother with new tools, performance improvements, and minimal breaking changes. If you're a Laravel developer, here's what you need to know.\n\n## What's New in Laravel 12?\n\n### 🚀 Modern Starter Kits\nLaravel 12 brings new starter kits for React, Vue, and Livewire. These kits come with:\n- **Inertia.js** for seamless single-page app experiences.\n- **TypeScript** for better maintainability.\n- **Tailwind CSS & ShadCN UI** for a sleek design.\n- **WorkOS AuthKit** (optional) for easy social login, passkeys, and SSO.\n\n### 🔥 Faster & More Efficient\n- **xxHash replaces MD5**, making hashing faster.\n- **UUID v7 support**, improving database indexing.\n- **MariaDB CLI Support**, so you can now use MariaDB natively in Laravel.\n- **Collection::range now includes a step parameter**, making sequence generation more flexible.\n\n### 🔧 Easier Debugging\n- **`debug()->suggest()`** helps identify issues faster by suggesting solutions in real-time.\n\n### 🔑 Stronger Password Security\n- **New password validation rules** to enforce stronger passwords.\n\n## How to Install Laravel 12\n\nGetting started with Laravel 12 is easy. Just follow these steps:\n\n1. **Install Laravel globally (if you haven't already):**\n   ```bash\n   composer global require laravel/installer\n   ```\n\n2. **Create a new Laravel 12 project:**\n   ```bash\n   laravel new myproject\n   cd myproject\n   ```\n\n3. **Install dependencies:**\n   ```bash\n   composer install\n   ```\n\n4. **Set up your environment file:**\n   ```bash\n   cp .env.example .env\n   ```\n   Configure your database and other settings in `.env`.\n\n5. **Generate an application key:**\n   ```bash\n   php artisan key:generate\n   ```\n\n6. **Run database migrations:**\n   ```bash\n   php artisan migrate\n   ```\n\n7. **Start the development server:**\n   ```bash\n   php artisan serve\n   ```\n   Your Laravel 12 app is now running at `http://localhost:8000`! 🎉\n\n## Why Upgrade to Laravel 12?\n- **Minimal breaking changes** – upgrading is easy.\n- **Better performance** with faster hashing and indexing.\n- **More tools for modern web apps** like React, Vue, and Livewire.\n- **Improved security** with stronger password validation.\n\n## License\nThis project is open-source and available under the MIT License.\n\nLaravel 12 makes development smoother and more powerful. Ready to build something amazing? 🚀\n\n",
            "url": "https://www.dibakarmitra.com/notes/laravel12",
            "title": "Laravel 12 – What's New & How to Get Started",
            "date_modified": "2025-03-11T00:00:00.000Z",
            "author": {
                "name": "Dibakar Mitra",
                "url": "https://www.dibakarmitra.com"
            },
            "tags": [
                "Laravel",
                "PHP",
                "Web Development",
                "Laravel 12"
            ]
        },
        {
            "id": "https://www.dibakarmitra.com/notes/web-security-best-practices",
            "content_html": "\n# Web Security Best Practices for Modern Applications\n\nSecurity is paramount in modern web applications. Let's explore essential practices to protect your applications.\n\n## Authentication\n\n### Secure Password Hashing\n\n```typescript\nimport * as bcrypt from 'bcrypt';\n\nasync function hashPassword(password: string): Promise<string> {\n  const saltRounds = 12;\n  return await bcrypt.hash(password, saltRounds);\n}\n\nasync function verifyPassword(password: string, hash: string): Promise<boolean> {\n  return await bcrypt.compare(password, hash);\n}\n```\n\n## JWT Implementation\n\n```typescript\nimport * as jwt from 'jsonwebtoken';\n\nconst JWT_SECRET = process.env.JWT_SECRET!;\n\ninterface TokenPayload {\n  userId: string;\n  role: string;\n}\n\nfunction generateToken(payload: TokenPayload): string {\n  return jwt.sign(payload, JWT_SECRET, {\n    expiresIn: '1h',\n    algorithm: 'HS256'\n  });\n}\n\nfunction verifyToken(token: string): TokenPayload {\n  try {\n    return jwt.verify(token, JWT_SECRET) as TokenPayload;\n  } catch (error) {\n    throw new Error('Invalid token');\n  }\n}\n```\n\n## XSS Prevention\n\n### Content Security Policy\n\n```typescript\n// Express middleware\napp.use((req, res, next) => {\n  res.setHeader(\n    'Content-Security-Policy',\n    \"default-src 'self'; \" +\n    \"script-src 'self' 'unsafe-inline' 'unsafe-eval'; \" +\n    \"style-src 'self' 'unsafe-inline';\"\n  );\n  next();\n});\n```\n\n### Input Sanitization\n\n```typescript\nimport { sanitize } from 'dompurify';\n\nfunction sanitizeUserInput(input: string): string {\n  return sanitize(input, {\n    ALLOWED_TAGS: ['b', 'i', 'em', 'strong', 'a'],\n    ALLOWED_ATTR: ['href']\n  });\n}\n\n// Usage in React\nfunction CommentDisplay({ comment }: { comment: string }) {\n  return <div dangerouslySetInnerHTML={{ \n    __html: sanitizeUserInput(comment) \n  }} />;\n}\n```\n\n## CSRF Protection\n\n```typescript\nimport csurf from 'csurf';\n\n// Express middleware\napp.use(csurf());\n\n// React component\nfunction Form() {\n  const csrfToken = document.querySelector('meta[name=\"csrf-token\"]')\n    ?.getAttribute('content');\n\n  return (\n    <form method=\"POST\" action=\"/api/submit\">\n      <input type=\"hidden\" name=\"_csrf\" value={csrfToken} />\n      {/* form fields */}\n    </form>\n  );\n}\n```\n\n## SQL Injection Prevention\n\n```typescript\nimport { Pool } from 'pg';\n\nconst pool = new Pool();\n\nasync function getUserById(id: string) {\n  // Use parameterized queries\n  const query = {\n    text: 'SELECT * FROM users WHERE id = $1',\n    values: [id],\n  };\n  \n  try {\n    const result = await pool.query(query);\n    return result.rows[0];\n  } catch (error) {\n    console.error('Database error:', error);\n    throw error;\n  }\n}\n```\n\n## Rate Limiting\n\n```typescript\nimport rateLimit from 'express-rate-limit';\n\nconst limiter = rateLimit({\n  windowMs: 15 * 60 * 1000, // 15 minutes\n  max: 100, // limit each IP to 100 requests per windowMs\n  message: 'Too many requests from this IP, please try again later'\n});\n\n// Apply to all routes\napp.use(limiter);\n\n// Apply to specific routes\napp.use('/api/login', rateLimit({\n  windowMs: 60 * 60 * 1000, // 1 hour\n  max: 5, // 5 attempts per hour\n  message: 'Too many login attempts, please try again later'\n}));\n```\n\n## Secure Headers\n\n```typescript\nimport helmet from 'helmet';\n\napp.use(helmet({\n  contentSecurityPolicy: {\n    directives: {\n      defaultSrc: [\"'self'\"],\n      scriptSrc: [\"'self'\", \"'unsafe-inline'\"],\n      styleSrc: [\"'self'\", \"'unsafe-inline'\"],\n      imgSrc: [\"'self'\", \"data:\", \"https:\"],\n    },\n  },\n  referrerPolicy: { policy: 'same-origin' }\n}));\n```\n\n## Best Practices\n\n1. Security Headers\n   - Use HTTPS\n   - Set secure cookies\n   - Implement HSTS\n   - Enable CORS properly\n\n2. Authentication\n   - Implement MFA\n   - Use secure session management\n   - Implement proper password policies\n   - Handle logout properly\n\n3. Data Protection\n   - Encrypt sensitive data\n   - Implement proper access control\n   - Regular security audits\n   - Keep dependencies updated\n\n## Security Checklist\n\n```typescript\ninterface SecurityChecklist {\n  authentication: {\n    passwordHashing: boolean;\n    mfa: boolean;\n    sessionManagement: boolean;\n  };\n  headers: {\n    https: boolean;\n    csp: boolean;\n    hsts: boolean;\n  };\n  dataProtection: {\n    encryption: boolean;\n    accessControl: boolean;\n    backups: boolean;\n  };\n}\n\nconst securityAudit: SecurityChecklist = {\n  authentication: {\n    passwordHashing: true,\n    mfa: true,\n    sessionManagement: true\n  },\n  headers: {\n    https: true,\n    csp: true,\n    hsts: true\n  },\n  dataProtection: {\n    encryption: true,\n    accessControl: true,\n    backups: true\n  }\n};\n```\n\n## Conclusion\n\nSecurity should be a continuous process, not a one-time implementation. Regular audits and updates are essential to maintain a secure application.\n",
            "url": "https://www.dibakarmitra.com/notes/web-security-best-practices",
            "title": "Web Security Best Practices for Modern Applications",
            "date_modified": "2024-10-25T00:00:00.000Z",
            "author": {
                "name": "Dibakar Mitra",
                "url": "https://www.dibakarmitra.com"
            },
            "tags": [
                "Security",
                "Web Development",
                "Authentication",
                "OWASP"
            ]
        },
        {
            "id": "https://www.dibakarmitra.com/notes/getting-started",
            "content_html": "\nNextfolio includes all the essentials for a stunning portfolio website.\n\nStart by [deploying](https://vercel.com/new/clone?repository-url=https%3A%2F%2Fgithub.com%2F1msirius%2FNextfolio) your portfolio with Vercel in minutes, or fork the [repository](https://github.com/1msirius/Nextfolio) and follow the instructions below to set it up.\n\n[![Deploy with Vercel](https://vercel.com/button)](https://vercel.com/new/clone?repository-url=https%3A%2F%2Fgithub.com%2F1msirius%2FNextfolio)\n\n## Installation\n\nNextfolio uses [pnpm](https://pnpm.io/installation) for dependency management, so ensure it is installed on your system.\n\nExecute [create-next-app](https://github.com/vercel/next.js/tree/canary/packages/create-next-app) with [pnpm](https://pnpm.io/installation) to bootstrap the example:\n\n```\npnpm create next-app --example https://github.com/1msirius/Nextfolio my-portfolio\n```\n\nStart the development server:\n\n```\npnpm dev\n```\n\nThe server will be running at [http://localhost:3000](http://localhost:3000).\n\n## Configuration\n\nCustomize your Nextfolio setup by updating your information to ensure proper SEO, feed generation, Open Graph integration, and other settings.\n\n### Config.ts\n\nUpdate the site metadata and social links in the **config/metadata.ts** file. These constants are utilized across the site for SEO, feeds, social links, and Open Graph integration.\n\n```\nexport const metaData = {\n  baseUrl: \"https://nextfolio-template.vercel.app\", // Update with your site base URL\n  title: \"Nextfolio\", // Update with your site title\n  name: \"Sirius\", // Update with your name\n  ogImage: \"/opengraph-image.png\", // Update with your Open Graph image\n  description:\n    \"A clean, fast, and lightweight portfolio template built with Next.js, Vercel, and Tailwind CSS for optimal performance.\", // Update with your site description\n};\n\nexport const socialLinks = {\n  twitter: \"https://x.com/1tssirius\", // Update with your Twitter URL\n  github: \"https://github.com/1msirius/Nextfolio\", // Update with your GitHub URL\n  instagram: \"https://www.instagram.com/\", // Update with your Instagram URL\n  linkedin: \"https://www.linkedin.com/\", // Update with your LinkedIn URL\n  email: \"mailto:example@gmail.com\", // Update with your email address\n};\n```\n\n### Sitemap\n\nAdjust the routes to match your portfolio’s navigation in **app/sitemap.ts** file for SEO optimization:\n\n```\nlet routes = [\"\", \"blog\", \"projects\", \"photos\"].map((route) => ({ // Update routes according to your navbar\n  url: `${BaseUrl}${route}`,\n  lastModified: new Date().toISOString().split(\"T\")[0],\n}));\n```\n\n### Profile Photo\n\nUpdate your profile photo by replacing the **public/profile.png** file with your image.\n\n### Favicon\n\nUpdate your favicon by replacing the **public/favicon.ico** file with your custom icon.\n\n## Analytics\n\nNextfolio uses [Vercel Web Analytics](https://vercel.com/docs/analytics/quickstart) and [Speed Insights](https://vercel.com/docs/speed-insights/quickstart) to monitor user interactions and website's performance. Simply deploy your site on Vercel and enable both features through the Vercel dashboard.\n\n## Ready!\n\nYou're all set! Update your blog posts in the **/content** folder, add your project data in **app/project/projectdata.tsx**, and update your images in **app/photos/page.tsx**.\n\nYour portfolio is equipped with SEO, [RSS](/rss.xml), [Atom](/atom.xml), and [JSON](/feed.json) feeds, as well as analytics. Nextfolio is fully customizable, allowing you to add features as needed.\n",
            "url": "https://www.dibakarmitra.com/notes/getting-started",
            "title": "Getting Started with Nextfolio",
            "summary": "Instructions to build and configure your Nextfolio portfolio.",
            "date_modified": "2024-08-13T00:00:00.000Z",
            "author": {
                "name": "Dibakar Mitra",
                "url": "https://www.dibakarmitra.com"
            },
            "tags": [
                "Configuration",
                "Web development"
            ]
        },
        {
            "id": "https://www.dibakarmitra.com/notes/getting-started-with-nextjs",
            "content_html": "\n# Getting Started with Next.js 14\n\nNext.js has revolutionized the way we build React applications. In this post, we'll explore the key features that make Next.js 14 stand out.\n\n## Why Next.js?\n\nNext.js provides an excellent developer experience with features like:\n\n- Server Components\n- App Router\n- Server Actions\n- Streaming\n- Built-in SEO Optimization\n\n## Getting Started\n\n```bash\nnpx create-next-app@latest my-app\ncd my-app\nnpm run dev\n```\n\n## Key Features\n\n### 1. Server Components\n\nServer Components allow you to write UI that can be rendered and cached on the server. This results in:\n\n- Smaller bundle sizes\n- Better initial page loads\n- Improved SEO\n\n### 2. App Router\n\nThe new App Router provides:\n\n- Nested layouts\n- Colocated components\n- Simplified routing\n\n## Conclusion\n\nNext.js 14 makes it easier than ever to build performant web applications. Give it a try in your next project!\n",
            "url": "https://www.dibakarmitra.com/notes/getting-started-with-nextjs",
            "title": "Getting Started with Next.js 14",
            "date_modified": "2024-03-15T00:00:00.000Z",
            "author": {
                "name": "Dibakar Mitra",
                "url": "https://www.dibakarmitra.com"
            },
            "tags": [
                "Next.js",
                "React",
                "Web Development"
            ]
        },
        {
            "id": "https://www.dibakarmitra.com/notes/mastering-typescript",
            "content_html": "\n# Mastering TypeScript in 2024\n\nTypeScript has become the go-to language for building scalable JavaScript applications. Let's dive into some advanced concepts.\n\n## Type System Fundamentals\n\nTypeScript's type system is powerful and flexible:\n\n```typescript\n// Basic Types\nlet name: string = 'John';\nlet age: number = 30;\nlet isActive: boolean = true;\n\n// Union Types\ntype Status = 'pending' | 'active' | 'completed';\nlet taskStatus: Status = 'pending';\n\n// Interfaces\ninterface User {\n  id: number;\n  name: string;\n  email: string;\n  role?: string;\n}\n```\n\n## Advanced Features\n\n### Generics\n\nGenerics make your code more reusable:\n\n```typescript\nfunction getFirst<T>(array: T[]): T | undefined {\n  return array[0];\n}\n\nconst first = getFirst([1, 2, 3]); // number\nconst firstString = getFirst(['a', 'b', 'c']); // string\n```\n\n### Utility Types\n\nTypeScript provides built-in utility types:\n\n```typescript\ninterface Todo {\n  title: string;\n  description: string;\n  completed: boolean;\n}\n\ntype TodoPreview = Pick<Todo, 'title' | 'completed'>;\ntype ReadonlyTodo = Readonly<Todo>;\n```\n\n## Best Practices\n\n1. Always use strict mode\n2. Leverage type inference\n3. Use interfaces for object shapes\n4. Implement proper error handling\n\n## Conclusion\n\nTypeScript continues to evolve and improve. Stay updated with the latest features to write better, safer code!\n",
            "url": "https://www.dibakarmitra.com/notes/mastering-typescript",
            "title": "Mastering TypeScript in 2024",
            "date_modified": "2024-03-10T00:00:00.000Z",
            "author": {
                "name": "Dibakar Mitra",
                "url": "https://www.dibakarmitra.com"
            },
            "tags": [
                "TypeScript",
                "JavaScript",
                "Programming"
            ]
        },
        {
            "id": "https://www.dibakarmitra.com/notes/tailwind-css-tips",
            "content_html": "\n# Advanced Tailwind CSS Tips and Tricks\n\nTailwind CSS has transformed the way we style web applications. Here are some advanced techniques to level up your Tailwind game.\n\n## Custom Configurations\n\nExtend Tailwind's default configuration:\n\n```javascript\n// tailwind.config.js\nmodule.exports = {\n  theme: {\n    extend: {\n      colors: {\n        primary: {\n          50: '#f0f9ff',\n          100: '#e0f2fe',\n          // ... other shades\n        }\n      },\n      spacing: {\n        '128': '32rem',\n      }\n    }\n  }\n}\n```\n\n## Responsive Design Patterns\n\n### Stack Pattern\n\n```html\n<div class=\"space-y-4 md:space-y-0 md:grid md:grid-cols-2 md:gap-6\">\n  <div class=\"p-4 bg-white shadow rounded\">Item 1</div>\n  <div class=\"p-4 bg-white shadow rounded\">Item 2</div>\n</div>\n```\n\n### Sidebar Pattern\n\n```html\n<div class=\"lg:grid lg:grid-cols-[300px_1fr] lg:gap-8\">\n  <nav class=\"hidden lg:block\">Sidebar</nav>\n  <main>Main Content</main>\n</div>\n```\n\n## Animation Classes\n\n```html\n<button class=\"transform transition hover:scale-105 active:scale-95\">\n  Animated Button\n</button>\n\n<div class=\"animate-bounce\">\n  Bouncing Element\n</div>\n```\n\n## Dark Mode\n\n```html\n<div class=\"bg-white dark:bg-gray-800 text-gray-900 dark:text-white\">\n  Automatic dark mode support\n</div>\n```\n\n## Best Practices\n\n1. Use consistent spacing scales\n2. Leverage component classes\n3. Utilize container queries\n4. Implement proper responsive breakpoints\n\n## Conclusion\n\nTailwind CSS provides powerful tools for building modern interfaces. Keep experimenting with these techniques to create better user experiences!\n",
            "url": "https://www.dibakarmitra.com/notes/tailwind-css-tips",
            "title": "Advanced Tailwind CSS Tips and Tricks",
            "date_modified": "2024-03-01T00:00:00.000Z",
            "author": {
                "name": "Dibakar Mitra",
                "url": "https://www.dibakarmitra.com"
            },
            "tags": [
                "Tailwind CSS",
                "CSS",
                "Web Design",
                "Frontend"
            ]
        },
        {
            "id": "https://www.dibakarmitra.com/notes/react-performance-optimization",
            "content_html": "\n# React Performance Optimization Techniques\n\nPerformance optimization is crucial for creating smooth, responsive React applications. Let's explore some advanced techniques.\n\n## 1. Memoization\n\n### Using useMemo\n\n```jsx\nconst memoizedValue = useMemo(() => computeExpensiveValue(a, b), [a, b]);\n```\n\n### Using React.memo\n\n```jsx\nconst MyComponent = React.memo(function MyComponent(props) {\n  return <div>{props.data}</div>;\n});\n```\n\n## 2. Code Splitting\n\n```jsx\nconst MyComponent = lazy(() => import('./MyComponent'));\n\nfunction App() {\n  return (\n    <Suspense fallback={<Loading />}>\n      <MyComponent />\n    </Suspense>\n  );\n}\n```\n\n## 3. Virtual Lists\n\nFor long lists, use virtualization:\n\n```jsx\nimport { FixedSizeList } from 'react-window';\n\nfunction Row({ index, style }) {\n  return <div style={style}>Row {index}</div>;\n}\n\nfunction List({ items }) {\n  return (\n    <FixedSizeList\n      height={400}\n      width={300}\n      itemCount={items.length}\n      itemSize={35}\n    >\n      {Row}\n    </FixedSizeList>\n  );\n}\n```\n\n## 4. Debouncing and Throttling\n\n```jsx\nimport { debounce } from 'lodash';\n\nfunction SearchComponent() {\n  const debouncedSearch = debounce((query) => {\n    // API call\n  }, 300);\n\n  return <input onChange={(e) => debouncedSearch(e.target.value)} />;\n}\n```\n\n## Best Practices\n\n1. Use Production Builds\n2. Implement Progressive Loading\n3. Optimize Images and Assets\n4. Monitor Bundle Size\n\n## Conclusion\n\nPerformance optimization is an ongoing process. Regular profiling and monitoring help maintain optimal application performance.\n",
            "url": "https://www.dibakarmitra.com/notes/react-performance-optimization",
            "title": "React Performance Optimization Techniques",
            "date_modified": "2024-02-25T00:00:00.000Z",
            "author": {
                "name": "Dibakar Mitra",
                "url": "https://www.dibakarmitra.com"
            },
            "tags": [
                "React",
                "Performance",
                "JavaScript",
                "Web Development"
            ]
        },
        {
            "id": "https://www.dibakarmitra.com/notes/modern-css-techniques",
            "content_html": "\n# Modern CSS Techniques for Better Web Design\n\nCSS has evolved significantly in recent years. Let's explore some modern techniques that can enhance your web designs.\n\n## CSS Grid Layout\n\nCreate complex layouts with minimal markup:\n\n```css\n.grid-container {\n  display: grid;\n  grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));\n  gap: 1rem;\n}\n```\n\n## CSS Custom Properties (Variables)\n\n```css\n:root {\n  --primary-color: #3490dc;\n  --spacing-unit: 1rem;\n}\n\n.card {\n  background: var(--primary-color);\n  padding: var(--spacing-unit);\n}\n\n@media (prefers-color-scheme: dark) {\n  :root {\n    --primary-color: #64b5f6;\n  }\n}\n```\n\n## Container Queries\n\n```css\n.card {\n  container-type: inline-size;\n}\n\n@container (min-width: 400px) {\n  .card-content {\n    display: grid;\n    grid-template-columns: 2fr 1fr;\n  }\n}\n```\n\n## Modern Selectors\n\n```css\n/* Has selector */\n.card:has(img) {\n  padding: 0;\n}\n\n/* Not selector */\n.card:not(:first-child) {\n  margin-top: 1rem;\n}\n\n/* Where selector */\n:where(.card, .box) {\n  border-radius: 0.5rem;\n}\n```\n\n## CSS Scroll Snap\n\n```css\n.scroll-container {\n  scroll-snap-type: x mandatory;\n  overflow-x: scroll;\n}\n\n.scroll-item {\n  scroll-snap-align: start;\n}\n```\n\n## CSS Animations\n\n```css\n@keyframes slide-in {\n  from {\n    transform: translateX(-100%);\n    opacity: 0;\n  }\n  to {\n    transform: translateX(0);\n    opacity: 1;\n  }\n}\n\n.animate-slide {\n  animation: slide-in 0.5s ease-out;\n}\n```\n\n## Best Practices\n\n1. Use Logical Properties\n2. Implement Progressive Enhancement\n3. Consider Accessibility\n4. Optimize Performance\n\n## Conclusion\n\nModern CSS provides powerful tools for creating sophisticated web designs. Keep exploring these features to enhance your development workflow!\n",
            "url": "https://www.dibakarmitra.com/notes/modern-css-techniques",
            "title": "Modern CSS Techniques for Better Web Design",
            "date_modified": "2024-02-20T00:00:00.000Z",
            "author": {
                "name": "Dibakar Mitra",
                "url": "https://www.dibakarmitra.com"
            },
            "tags": [
                "CSS",
                "Web Design",
                "Frontend",
                "Responsive Design"
            ]
        },
        {
            "id": "https://www.dibakarmitra.com/notes/web-animation-techniques",
            "content_html": "\n# Modern Web Animation Techniques\n\nCreating smooth, performant animations is crucial for modern web applications. Let's explore various techniques and best practices.\n\n## CSS Animations\n\n### Basic Keyframe Animations\n\n```css\n@keyframes slideIn {\n  from {\n    transform: translateX(-100%);\n    opacity: 0;\n  }\n  to {\n    transform: translateX(0);\n    opacity: 1;\n  }\n}\n\n.slide-in {\n  animation: slideIn 0.3s ease-out forwards;\n}\n```\n\n### CSS Transitions\n\n```css\n.button {\n  transition: transform 0.2s ease-in-out;\n}\n\n.button:hover {\n  transform: scale(1.05);\n}\n```\n\n## JavaScript Animations\n\n### Web Animations API\n\n```javascript\nelement.animate([\n  { transform: 'scale(1)', opacity: 1 },\n  { transform: 'scale(1.5)', opacity: 0 }\n], {\n  duration: 300,\n  easing: 'ease-in-out',\n  fill: 'forwards'\n});\n```\n\n### RequestAnimationFrame\n\n```javascript\nfunction animate(element) {\n  let start;\n\n  function step(timestamp) {\n    if (!start) start = timestamp;\n    const progress = timestamp - start;\n\n    element.style.transform = `translateX(${Math.min(progress / 10, 200)}px)`;\n\n    if (progress < 2000) {\n      requestAnimationFrame(step);\n    }\n  }\n\n  requestAnimationFrame(step);\n}\n```\n\n## Animation Libraries\n\n### Framer Motion\n\n```jsx\nimport { motion } from 'framer-motion';\n\nfunction AnimatedComponent() {\n  return (\n    <motion.div\n      initial={{ opacity: 0, y: 20 }}\n      animate={{ opacity: 1, y: 0 }}\n      transition={{ duration: 0.5 }}\n    >\n      Smooth entrance!\n    </motion.div>\n  );\n}\n```\n\n### GSAP (GreenSock)\n\n```javascript\nimport gsap from 'gsap';\n\ngsap.to('.element', {\n  duration: 1,\n  x: 100,\n  y: 50,\n  rotation: 360,\n  ease: 'power2.inOut'\n});\n```\n\n## Performance Optimization\n\n1. **Use Transform and Opacity**\n   - These properties are GPU-accelerated\n   - Avoid animating layout properties\n\n2. **Debounce and Throttle**\n   ```javascript\n   function debounce(func, wait) {\n     let timeout;\n     return function executedFunction(...args) {\n       const later = () => {\n         clearTimeout(timeout);\n         func(...args);\n       };\n       clearTimeout(timeout);\n       timeout = setTimeout(later, wait);\n     };\n   }\n   ```\n\n3. **Will-change Property**\n   ```css\n   .animated-element {\n     will-change: transform;\n   }\n   ```\n\n## Accessibility Considerations\n\n1. **Respect User Preferences**\n   ```css\n   @media (prefers-reduced-motion: reduce) {\n     * {\n       animation-duration: 0.01ms !important;\n       animation-iteration-count: 1 !important;\n       transition-duration: 0.01ms !important;\n       scroll-behavior: auto !important;\n     }\n   }\n   ```\n\n2. **ARIA Labels**\n   ```html\n   <div \n     role=\"alert\"\n     aria-live=\"polite\"\n     className=\"animated-notification\"\n   >\n     New message received\n   </div>\n   ```\n\n## Best Practices\n\n1. Keep animations subtle and purposeful\n2. Use appropriate timing functions\n3. Consider mobile performance\n4. Test across different browsers\n5. Implement fallbacks for older browsers\n\n## Conclusion\n\nModern web animations can significantly enhance user experience when implemented correctly. By following these techniques and best practices, you can create smooth, performant, and accessible animations that delight your users without compromising performance.",
            "url": "https://www.dibakarmitra.com/notes/web-animation-techniques",
            "title": "Modern Web Animation Techniques",
            "date_modified": "2024-02-20T00:00:00.000Z",
            "author": {
                "name": "Dibakar Mitra",
                "url": "https://www.dibakarmitra.com"
            },
            "tags": [
                "Animation",
                "CSS",
                "JavaScript",
                "Web Development"
            ]
        },
        {
            "id": "https://www.dibakarmitra.com/notes/graphql-best-practices",
            "content_html": "\n# GraphQL Best Practices and Advanced Patterns\n\nGraphQL has transformed how we build APIs. Let's explore advanced patterns and best practices.\n\n## Schema Design\n\n### Type Definitions\n\n```graphql\ntype User {\n  id: ID!\n  name: String!\n  email: String!\n  posts: [Post!]!\n  profile: Profile\n}\n\ntype Post {\n  id: ID!\n  title: String!\n  content: String!\n  author: User!\n  comments: [Comment!]!\n}\n\ntype Profile {\n  bio: String\n  avatar: String\n  socialLinks: [SocialLink!]\n}\n```\n\n## Query Optimization\n\n### Field Selection\n\n```graphql\nquery GetUserWithPosts {\n  user(id: \"123\") {\n    name\n    posts(first: 5) {\n      title\n      comments {\n        content\n      }\n    }\n  }\n}\n```\n\n### Using Fragments\n\n```graphql\nfragment UserFields on User {\n  id\n  name\n  email\n}\n\nquery GetUsers {\n  users {\n    ...UserFields\n    posts {\n      title\n    }\n  }\n}\n```\n\n## Mutations\n\n### Input Types\n\n```graphql\ninput CreatePostInput {\n  title: String!\n  content: String!\n  tags: [String!]\n}\n\ntype Mutation {\n  createPost(input: CreatePostInput!): Post!\n}\n```\n\n## Error Handling\n\n```graphql\ntype Error {\n  message: String!\n  code: String!\n  path: [String!]\n}\n\ntype PostResult {\n  success: Boolean!\n  post: Post\n  errors: [Error!]\n}\n\ntype Mutation {\n  createPost(input: CreatePostInput!): PostResult!\n}\n```\n\n## N+1 Problem Solution\n\n```typescript\nconst resolvers = {\n  User: {\n    posts: async (parent, args, context, info) => {\n      return context.dataloaders.posts.load(parent.id);\n    }\n  }\n};\n```\n\n## Best Practices\n\n1. Use DataLoaders for Batching\n2. Implement Proper Pagination\n3. Consider Query Complexity\n4. Cache Effectively\n\n## Security Considerations\n\n1. Rate Limiting\n2. Query Depth Limiting\n3. Field Authorization\n4. Input Validation\n\n## Conclusion\n\nGraphQL provides powerful tools for building flexible APIs. Following these patterns ensures scalable and maintainable applications.\n",
            "url": "https://www.dibakarmitra.com/notes/graphql-best-practices",
            "title": "GraphQL Best Practices and Advanced Patterns",
            "date_modified": "2024-02-15T00:00:00.000Z",
            "author": {
                "name": "Dibakar Mitra",
                "url": "https://www.dibakarmitra.com"
            },
            "tags": [
                "GraphQL",
                "API",
                "Backend",
                "Web Development"
            ]
        },
        {
            "id": "https://www.dibakarmitra.com/notes/web3-development-guide",
            "content_html": "\n# Web3 Development Guide: Building for the Decentralized Web\n\nWeb3 represents the next evolution of the internet, focusing on decentralization, blockchain technology, and user ownership. This guide will help you understand the fundamentals and get started with Web3 development.\n\n## Understanding Web3 Fundamentals\n\n### What is Web3?\n\nWeb3 refers to a decentralized version of the internet built on blockchain technology. Key characteristics include:\n\n- Decentralization\n- Trustless systems\n- Native payments\n- User ownership\n- Permissionless access\n\n### Core Technologies\n\n1. **Blockchain**\n   - Distributed ledger technology\n   - Consensus mechanisms\n   - Cryptographic security\n\n2. **Smart Contracts**\n   - Self-executing contracts\n   - Automated transactions\n   - Decentralized logic\n\n## Getting Started with Web3 Development\n\n### Setting Up Your Development Environment\n\n```bash\n# Install Node.js and npm\nnpm install -g truffle\nnpm install -g ganache-cli\n\n# Install MetaMask browser extension\n# Create a new wallet and save the seed phrase\n```\n\n### Essential Tools\n\n1. **Development Frameworks**\n   - Truffle\n   - Hardhat\n   - Brownie (Python)\n\n2. **Testing Networks**\n   - Ganache\n   - Testnet (Rinkeby, Ropsten)\n   - Local blockchain\n\n## Smart Contract Development\n\n### Writing Your First Smart Contract\n\n```solidity\n// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\ncontract SimpleStorage {\n    uint256 private storedData;\n    \n    function set(uint256 x) public {\n        storedData = x;\n    }\n    \n    function get() public view returns (uint256) {\n        return storedData;\n    }\n}\n```\n\n### Testing Smart Contracts\n\n```javascript\nconst SimpleStorage = artifacts.require(\"SimpleStorage\");\n\ncontract(\"SimpleStorage\", accounts => {\n  it(\"should store the value 89\", async () => {\n    const instance = await SimpleStorage.deployed();\n    await instance.set(89);\n    const storedData = await instance.get();\n    assert.equal(storedData, 89);\n  });\n});\n```\n\n## Building Decentralized Applications (dApps)\n\n### Frontend Integration\n\n```javascript\n// Using ethers.js\nimport { ethers } from 'ethers';\n\nasync function connectWallet() {\n  if (typeof window.ethereum !== 'undefined') {\n    try {\n      await window.ethereum.request({ method: 'eth_requestAccounts' });\n      const provider = new ethers.providers.Web3Provider(window.ethereum);\n      const signer = provider.getSigner();\n      return signer;\n    } catch (error) {\n      console.error(\"User denied account access\");\n    }\n  }\n}\n```\n\n### Interacting with Smart Contracts\n\n```javascript\nconst contract = new ethers.Contract(\n  contractAddress,\n  contractABI,\n  signer\n);\n\nasync function setValue(value) {\n  try {\n    const tx = await contract.set(value);\n    await tx.wait();\n    console.log(\"Value set successfully\");\n  } catch (error) {\n    console.error(\"Error:\", error);\n  }\n}\n```\n\n## Web3 Security Best Practices\n\n1. **Smart Contract Security**\n   - Audit your contracts\n   - Use established patterns\n   - Test thoroughly\n   - Consider gas optimization\n\n2. **Frontend Security**\n   - Validate user input\n   - Secure key management\n   - Handle errors gracefully\n\n## Advanced Topics\n\n### 1. DeFi Development\n\n```solidity\ncontract Token is ERC20 {\n    constructor(uint256 initialSupply) ERC20(\"MyToken\", \"MTK\") {\n        _mint(msg.sender, initialSupply);\n    }\n}\n```\n\n### 2. NFT Development\n\n```solidity\ncontract NFT is ERC721 {\n    constructor() ERC721(\"MyNFT\", \"MNFT\") {}\n    \n    function mint(address to, uint256 tokenId) public {\n        _safeMint(to, tokenId);\n    }\n}\n```\n\n### 3. DAOs and Governance\n\n```solidity\ncontract DAO {\n    struct Proposal {\n        string description;\n        uint256 voteCount;\n        bool executed;\n    }\n    \n    mapping(uint256 => Proposal) public proposals;\n}\n```\n\n## Tools and Resources\n\n1. **Development Tools**\n   - Remix IDE\n   - Web3.js\n   - Ethers.js\n   - OpenZeppelin\n\n2. **Testing and Deployment**\n   - Infura\n   - Alchemy\n   - IPFS\n\n## Best Practices\n\n1. **Code Quality**\n   - Follow Solidity style guide\n   - Document your code\n   - Use design patterns\n\n2. **Gas Optimization**\n   - Minimize storage operations\n   - Batch operations\n   - Use appropriate data types\n\n3. **User Experience**\n   - Handle network changes\n   - Provide clear feedback\n   - Implement proper error handling\n\n## Conclusion\n\nWeb3 development is an exciting and rapidly evolving field. By understanding these fundamentals and following best practices, you can build secure and efficient decentralized applications. Remember to stay updated with the latest developments in the ecosystem and always prioritize security in your applications.",
            "url": "https://www.dibakarmitra.com/notes/web3-development-guide",
            "title": "Web3 Development Guide: Building for the Decentralized Web",
            "date_modified": "2024-02-15T00:00:00.000Z",
            "author": {
                "name": "Dibakar Mitra",
                "url": "https://www.dibakarmitra.com"
            },
            "tags": [
                "Web3",
                "Blockchain",
                "Ethereum",
                "Smart Contracts",
                "DApp"
            ]
        },
        {
            "id": "https://www.dibakarmitra.com/notes/docker-microservices",
            "content_html": "\n# Docker and Microservices Architecture\n\nLearn how to build and deploy scalable microservices using Docker and modern container orchestration tools.\n\n## Docker Basics\n\n### Dockerfile Example\n\n```dockerfile\nFROM node:18-alpine\n\nWORKDIR /app\n\nCOPY package*.json ./\nRUN npm install\n\nCOPY . .\n\nEXPOSE 3000\nCMD [\"npm\", \"start\"]\n```\n\n## Docker Compose\n\n```yaml\nversion: '3.8'\nservices:\n  api:\n    build: ./api\n    ports:\n      - \"3000:3000\"\n    environment:\n      - DATABASE_URL=postgres://user:pass@db:5432/mydb\n    depends_on:\n      - db\n  \n  db:\n    image: postgres:14\n    environment:\n      - POSTGRES_USER=user\n      - POSTGRES_PASSWORD=pass\n      - POSTGRES_DB=mydb\n```\n\n## Microservices Communication\n\n### API Gateway Pattern\n\n```typescript\n// API Gateway\napp.get('/orders/:id', async (req, res) => {\n  const orderId = req.params.id;\n  const order = await orderService.getOrder(orderId);\n  const user = await userService.getUser(order.userId);\n  const payment = await paymentService.getPayment(order.paymentId);\n  \n  res.json({\n    ...order,\n    user,\n    payment\n  });\n});\n```\n\n## Service Discovery\n\n```yaml\napiVersion: v1\nkind: Service\nmetadata:\n  name: api-service\nspec:\n  selector:\n    app: api\n  ports:\n    - protocol: TCP\n      port: 80\n      targetPort: 3000\n  type: LoadBalancer\n```\n\n## Best Practices\n\n1. Use Multi-Stage Builds\n2. Implement Health Checks\n3. Follow the Twelve-Factor App Methodology\n4. Implement Circuit Breakers\n\n## Monitoring and Logging\n\n```yaml\n# Prometheus configuration\nscrape_configs:\n  - job_name: 'api'\n    static_configs:\n      - targets: ['api:3000']\n```\n\n## Security Best Practices\n\n1. Use Minimal Base Images\n2. Implement Least Privilege\n3. Scan for Vulnerabilities\n4. Secure Service Communication\n\n## Conclusion\n\nDocker and microservices provide a powerful foundation for building scalable applications. Remember to focus on security, monitoring, and maintainability.\n",
            "url": "https://www.dibakarmitra.com/notes/docker-microservices",
            "title": "Docker and Microservices Architecture",
            "date_modified": "2024-02-10T00:00:00.000Z",
            "author": {
                "name": "Dibakar Mitra",
                "url": "https://www.dibakarmitra.com"
            },
            "tags": [
                "Docker",
                "Microservices",
                "DevOps",
                "Kubernetes"
            ]
        },
        {
            "id": "https://www.dibakarmitra.com/notes/modern-testing-practices",
            "content_html": "\n# Modern Testing Practices in Web Development\n\nEffective testing is crucial for maintaining code quality and preventing regressions. Let's explore modern testing approaches.\n\n## Unit Testing with Jest\n\n### Testing React Components\n\n```jsx\nimport { render, screen, fireEvent } from '@testing-library/react';\nimport Counter from './Counter';\n\ndescribe('Counter Component', () => {\n  test('increments counter on button click', () => {\n    render(<Counter />);\n    const button = screen.getByRole('button', { name: /increment/i });\n    const count = screen.getByText(/count:/i);\n    \n    expect(count).toHaveTextContent('Count: 0');\n    fireEvent.click(button);\n    expect(count).toHaveTextContent('Count: 1');\n  });\n});\n```\n\n## Integration Testing\n\n```typescript\ndescribe('UserService', () => {\n  let userService: UserService;\n  let dbConnection: Database;\n\n  beforeEach(async () => {\n    dbConnection = await createTestDatabase();\n    userService = new UserService(dbConnection);\n  });\n\n  test('creates and retrieves user', async () => {\n    const userData = {\n      name: 'John Doe',\n      email: 'john@example.com'\n    };\n\n    const user = await userService.createUser(userData);\n    const retrieved = await userService.getUserById(user.id);\n\n    expect(retrieved).toMatchObject(userData);\n  });\n});\n```\n\n## E2E Testing with Cypress\n\n```javascript\ndescribe('Shopping Cart', () => {\n  beforeEach(() => {\n    cy.visit('/');\n    cy.login();\n  });\n\n  it('adds item to cart', () => {\n    cy.get('[data-testid=\"product-item\"]').first().click();\n    cy.get('[data-testid=\"add-to-cart\"]').click();\n    cy.get('[data-testid=\"cart-count\"]').should('have.text', '1');\n  });\n\n  it('completes checkout process', () => {\n    cy.addItemToCart();\n    cy.get('[data-testid=\"checkout\"]').click();\n    cy.fillShippingDetails();\n    cy.get('[data-testid=\"submit-order\"]').click();\n    cy.url().should('include', '/order-confirmation');\n  });\n});\n```\n\n## API Testing\n\n```typescript\nimport supertest from 'supertest';\nimport app from './app';\n\ndescribe('API Endpoints', () => {\n  const request = supertest(app);\n\n  test('GET /api/users returns users list', async () => {\n    const response = await request\n      .get('/api/users')\n      .expect('Content-Type', /json/)\n      .expect(200);\n\n    expect(response.body).toBeInstanceOf(Array);\n  });\n\n  test('POST /api/users creates new user', async () => {\n    const userData = {\n      name: 'Jane Doe',\n      email: 'jane@example.com'\n    };\n\n    const response = await request\n      .post('/api/users')\n      .send(userData)\n      .expect(201);\n\n    expect(response.body).toMatchObject(userData);\n  });\n});\n```\n\n## Test Coverage\n\n```javascript\n// jest.config.js\nmodule.exports = {\n  collectCoverage: true,\n  coverageThreshold: {\n    global: {\n      branches: 80,\n      functions: 80,\n      lines: 80,\n      statements: 80\n    }\n  }\n};\n```\n\n## Best Practices\n\n1. Follow the Testing Pyramid\n2. Write Maintainable Tests\n3. Use Test Doubles Appropriately\n4. Implement Continuous Integration\n\n## Testing Strategies\n\n1. Test-Driven Development (TDD)\n2. Behavior-Driven Development (BDD)\n3. Property-Based Testing\n4. Visual Regression Testing\n\n## Conclusion\n\nEffective testing is an investment in code quality and team productivity. Choose the right testing strategies and tools for your project's needs.\n",
            "url": "https://www.dibakarmitra.com/notes/modern-testing-practices",
            "title": "Modern Testing Practices in Web Development",
            "date_modified": "2024-02-05T00:00:00.000Z",
            "author": {
                "name": "Dibakar Mitra",
                "url": "https://www.dibakarmitra.com"
            },
            "tags": [
                "Testing",
                "Jest",
                "Cypress",
                "TDD"
            ]
        },
        {
            "id": "https://www.dibakarmitra.com/notes/state-management-patterns",
            "content_html": "\n# Modern State Management Patterns in React\n\nState management is a crucial aspect of modern web applications. Let's explore different patterns and solutions.\n\n## React Context API\n\n```tsx\n// Create context\nconst ThemeContext = createContext<{\n  theme: string;\n  setTheme: (theme: string) => void;\n}>({\n  theme: 'light',\n  setTheme: () => {}\n});\n\n// Provider component\nexport function ThemeProvider({ children }: { children: React.ReactNode }) {\n  const [theme, setTheme] = useState('light');\n\n  return (\n    <ThemeContext.Provider value={{ theme, setTheme }}>\n      {children}\n    </ThemeContext.Provider>\n  );\n}\n\n// Usage in components\nfunction ThemeToggle() {\n  const { theme, setTheme } = useContext(ThemeContext);\n  \n  return (\n    <button onClick={() => setTheme(theme === 'light' ? 'dark' : 'light')}>\n      Toggle Theme\n    </button>\n  );\n}\n```\n\n## Redux Toolkit\n\n```typescript\n// Store slice\nimport { createSlice, PayloadAction } from '@reduxjs/toolkit';\n\ninterface CartState {\n  items: CartItem[];\n  total: number;\n}\n\nconst cartSlice = createSlice({\n  name: 'cart',\n  initialState: { items: [], total: 0 } as CartState,\n  reducers: {\n    addItem: (state, action: PayloadAction<CartItem>) => {\n      state.items.push(action.payload);\n      state.total += action.payload.price;\n    },\n    removeItem: (state, action: PayloadAction<string>) => {\n      const item = state.items.find(item => item.id === action.payload);\n      if (item) {\n        state.total -= item.price;\n        state.items = state.items.filter(item => item.id !== action.payload);\n      }\n    }\n  }\n});\n\n// Usage in components\nfunction CartComponent() {\n  const cart = useSelector((state: RootState) => state.cart);\n  const dispatch = useDispatch();\n\n  return (\n    <div>\n      <h2>Cart Total: ${cart.total}</h2>\n      {cart.items.map(item => (\n        <div key={item.id}>\n          <span>{item.name}</span>\n          <button onClick={() => dispatch(removeItem(item.id))}>\n            Remove\n          </button>\n        </div>\n      ))}\n    </div>\n  );\n}\n```\n\n## Zustand\n\n```typescript\nimport create from 'zustand';\n\ninterface UserStore {\n  user: User | null;\n  setUser: (user: User | null) => void;\n  logout: () => void;\n}\n\nconst useUserStore = create<UserStore>((set) => ({\n  user: null,\n  setUser: (user) => set({ user }),\n  logout: () => set({ user: null })\n}));\n\n// Usage\nfunction UserProfile() {\n  const { user, logout } = useUserStore();\n\n  if (!user) return <LoginButton />;\n\n  return (\n    <div>\n      <h2>Welcome, {user.name}</h2>\n      <button onClick={logout}>Logout</button>\n    </div>\n  );\n}\n```\n\n## Jotai\n\n```typescript\nimport { atom, useAtom } from 'jotai';\n\nconst counterAtom = atom(0);\nconst doubleAtom = atom((get) => get(counterAtom) * 2);\n\nfunction Counter() {\n  const [count, setCount] = useAtom(counterAtom);\n  const [double] = useAtom(doubleAtom);\n\n  return (\n    <div>\n      <h2>Count: {count}</h2>\n      <h3>Double: {double}</h3>\n      <button onClick={() => setCount(c => c + 1)}>\n        Increment\n      </button>\n    </div>\n  );\n}\n```\n\n## Best Practices\n\n1. Choose the Right Tool\n   - Small apps: React Context/useState\n   - Medium apps: Zustand/Jotai\n   - Large apps: Redux Toolkit\n\n2. State Organization\n   - Keep state close to where it's used\n   - Split global state into domains\n   - Use selectors for derived state\n\n3. Performance Optimization\n   - Memoize selectors\n   - Use context splitting\n   - Implement proper re-render prevention\n\n## Common Patterns\n\n### Command Pattern\n\n```typescript\ntype Command = {\n  type: string;\n  payload?: any;\n};\n\nfunction commandReducer(state: State, command: Command) {\n  switch (command.type) {\n    case 'ADD_ITEM':\n      return {\n        ...state,\n        items: [...state.items, command.payload]\n      };\n    // ... other cases\n  }\n}\n```\n\n### Observer Pattern\n\n```typescript\nconst createStore = <T>(initialState: T) => {\n  let state = initialState;\n  const listeners = new Set<(state: T) => void>();\n\n  return {\n    getState: () => state,\n    setState: (newState: T) => {\n      state = newState;\n      listeners.forEach(listener => listener(state));\n    },\n    subscribe: (listener: (state: T) => void) => {\n      listeners.add(listener);\n      return () => listeners.delete(listener);\n    }\n  };\n};\n```\n\n## Conclusion\n\nChoose the right state management solution based on your application's needs. Consider factors like team size, application complexity, and performance requirements.\n",
            "url": "https://www.dibakarmitra.com/notes/state-management-patterns",
            "title": "Modern State Management Patterns in React",
            "date_modified": "2024-01-30T00:00:00.000Z",
            "author": {
                "name": "Dibakar Mitra",
                "url": "https://www.dibakarmitra.com"
            },
            "tags": [
                "React",
                "State Management",
                "Redux",
                "Zustand"
            ]
        },
        {
            "id": "https://www.dibakarmitra.com/notes/web-accessibility-guide",
            "content_html": "\n# Web Accessibility Guide: Building Inclusive Applications\n\nCreating accessible web applications is not just a legal requirement but a moral imperative. Let's explore how to make our applications work for everyone.\n\n## Semantic HTML\n\n```html\n<!-- Bad -->\n<div class=\"button\" onclick=\"submit()\">\n  Submit Form\n</div>\n\n<!-- Good -->\n<button type=\"submit\" aria-label=\"Submit form\">\n  Submit Form\n</button>\n\n<!-- Bad -->\n<div class=\"header\">\n  <div class=\"nav\">...</div>\n</div>\n\n<!-- Good -->\n<header>\n  <nav aria-label=\"Main navigation\">...</nav>\n</header>\n```\n\n## ARIA Attributes\n\n```jsx\n// React component with ARIA attributes\nfunction Accordion({ items }) {\n  const [activeIndex, setActiveIndex] = useState(null);\n\n  return (\n    <div role=\"region\" aria-label=\"FAQ Accordion\">\n      {items.map((item, index) => (\n        <div key={index}>\n          <button\n            aria-expanded={activeIndex === index}\n            aria-controls={`content-${index}`}\n            onClick={() => setActiveIndex(index)}\n          >\n            {item.title}\n          </button>\n          <div\n            id={`content-${index}`}\n            role=\"region\"\n            aria-hidden={activeIndex !== index}\n          >\n            {item.content}\n          </div>\n        </div>\n      ))}\n    </div>\n  );\n}\n```\n\n## Focus Management\n\n```typescript\nfunction Modal({ isOpen, onClose, children }) {\n  const modalRef = useRef<HTMLDivElement>(null);\n\n  useEffect(() => {\n    if (isOpen) {\n      // Store the element that had focus before opening modal\n      const previousFocus = document.activeElement;\n      \n      // Focus the modal\n      modalRef.current?.focus();\n\n      // Restore focus when modal closes\n      return () => {\n        (previousFocus as HTMLElement)?.focus();\n      };\n    }\n  }, [isOpen]);\n\n  return isOpen ? (\n    <div\n      ref={modalRef}\n      role=\"dialog\"\n      aria-modal=\"true\"\n      tabIndex={-1}\n      aria-labelledby=\"modal-title\"\n    >\n      <h2 id=\"modal-title\">Modal Title</h2>\n      {children}\n      <button onClick={onClose}>Close</button>\n    </div>\n  ) : null;\n}\n```\n\n## Skip Links\n\n```tsx\nfunction SkipLink() {\n  return (\n    <a\n      href=\"#main-content\"\n      className=\"skip-link\"\n      style={{\n        position: 'absolute',\n        top: -40,\n        left: 0,\n        padding: 8,\n        zIndex: 100,\n        ':focus': {\n          top: 0,\n        },\n      }}\n    >\n      Skip to main content\n    </a>\n  );\n}\n```\n\n## Color Contrast\n\n```typescript\nfunction isColorContrastValid(foreground: string, background: string): boolean {\n  const luminance = (r: number, g: number, b: number) => {\n    const [rs, gs, bs] = [r, g, b].map(c => {\n      c = c / 255;\n      return c <= 0.03928\n        ? c / 12.92\n        : Math.pow((c + 0.055) / 1.055, 2.4);\n    });\n    return 0.2126 * rs + 0.7152 * gs + 0.0722 * bs;\n  };\n\n  const hex2rgb = (hex: string) => {\n    const result = /^#?([a-f\\d]{2})([a-f\\d]{2})([a-f\\d]{2})$/i.exec(hex);\n    return result\n      ? [\n          parseInt(result[1], 16),\n          parseInt(result[2], 16),\n          parseInt(result[3], 16),\n        ]\n      : null;\n  };\n\n  const fg = hex2rgb(foreground);\n  const bg = hex2rgb(background);\n\n  if (!fg || !bg) return false;\n\n  const l1 = luminance(fg[0], fg[1], fg[2]);\n  const l2 = luminance(bg[0], bg[1], bg[2]);\n\n  const ratio = (Math.max(l1, l2) + 0.05) / (Math.min(l1, l2) + 0.05);\n  return ratio >= 4.5; // WCAG AA standard for normal text\n}\n```\n\n## Keyboard Navigation\n\n```tsx\nfunction KeyboardNavList({ items }) {\n  const [selectedIndex, setSelectedIndex] = useState(0);\n\n  const handleKeyDown = (event: React.KeyboardEvent) => {\n    switch (event.key) {\n      case 'ArrowDown':\n        event.preventDefault();\n        setSelectedIndex(i => Math.min(i + 1, items.length - 1));\n        break;\n      case 'ArrowUp':\n        event.preventDefault();\n        setSelectedIndex(i => Math.max(i - 1, 0));\n        break;\n    }\n  };\n\n  return (\n    <ul role=\"listbox\" onKeyDown={handleKeyDown}>\n      {items.map((item, index) => (\n        <li\n          key={index}\n          role=\"option\"\n          aria-selected={index === selectedIndex}\n          tabIndex={index === selectedIndex ? 0 : -1}\n        >\n          {item.label}\n        </li>\n      ))}\n    </ul>\n  );\n}\n```\n\n## Form Accessibility\n\n```tsx\nfunction AccessibleForm() {\n  return (\n    <form aria-labelledby=\"form-title\">\n      <h2 id=\"form-title\">Contact Us</h2>\n      \n      <div>\n        <label htmlFor=\"name\">\n          Name\n          <span aria-hidden=\"true\">*</span>\n          <span className=\"sr-only\">required</span>\n        </label>\n        <input\n          id=\"name\"\n          type=\"text\"\n          required\n          aria-required=\"true\"\n          aria-describedby=\"name-error\"\n        />\n        <div id=\"name-error\" role=\"alert\"></div>\n      </div>\n\n      <div>\n        <label htmlFor=\"email\">Email</label>\n        <input\n          id=\"email\"\n          type=\"email\"\n          aria-describedby=\"email-hint\"\n        />\n        <div id=\"email-hint\" className=\"hint\">\n          We'll never share your email\n        </div>\n      </div>\n    </form>\n  );\n}\n```\n\n## Best Practices\n\n1. Semantic HTML\n   - Use proper heading hierarchy\n   - Use semantic elements\n   - Provide alternative text for images\n\n2. Keyboard Navigation\n   - Ensure all interactive elements are focusable\n   - Implement logical tab order\n   - Provide visible focus indicators\n\n3. ARIA Implementation\n   - Use ARIA labels when needed\n   - Implement proper roles\n   - Manage dynamic content updates\n\n4. Testing\n   - Use screen readers\n   - Keyboard navigation testing\n   - Automated accessibility testing\n\n## Conclusion\n\nAccessibility should be considered from the start of development, not as an afterthought. Following these practices ensures your application is usable by everyone.\n",
            "url": "https://www.dibakarmitra.com/notes/web-accessibility-guide",
            "title": "Web Accessibility Guide: Building Inclusive Applications",
            "date_modified": "2024-01-20T00:00:00.000Z",
            "author": {
                "name": "Dibakar Mitra",
                "url": "https://www.dibakarmitra.com"
            },
            "tags": [
                "Accessibility",
                "WCAG",
                "Web Development",
                "UX"
            ]
        },
        {
            "id": "https://www.dibakarmitra.com/notes/advanced-react-hooks",
            "content_html": "\nA comprehensive guide to advanced React hooks patterns, including custom hooks development, performance optimization, and best practices for state management.",
            "url": "https://www.dibakarmitra.com/notes/advanced-react-hooks",
            "title": "Advanced React Hooks: Beyond the Basics",
            "date_modified": "2024-01-15T00:00:00.000Z",
            "author": {
                "name": "Dibakar Mitra",
                "url": "https://www.dibakarmitra.com"
            },
            "tags": [
                "react",
                "hooks",
                "javascript"
            ]
        },
        {
            "id": "https://www.dibakarmitra.com/notes/system-design-principles",
            "content_html": "\n# System Design Principles and Best Practices\n\nUnderstanding system design principles is crucial for building scalable, reliable applications. Let's explore key concepts and patterns.\n\n## Load Balancing\n\n```typescript\n// Load Balancer Interface\ninterface LoadBalancer {\n  addServer(server: Server): void;\n  removeServer(server: Server): void;\n  getNextServer(): Server;\n}\n\n// Round Robin Implementation\nclass RoundRobinLoadBalancer implements LoadBalancer {\n  private servers: Server[] = [];\n  private currentIndex = 0;\n\n  addServer(server: Server): void {\n    this.servers.push(server);\n  }\n\n  removeServer(server: Server): void {\n    this.servers = this.servers.filter(s => s.id !== server.id);\n  }\n\n  getNextServer(): Server {\n    if (this.servers.length === 0) {\n      throw new Error('No servers available');\n    }\n\n    const server = this.servers[this.currentIndex];\n    this.currentIndex = (this.currentIndex + 1) % this.servers.length;\n    return server;\n  }\n}\n```\n\n## Caching Strategy\n\n```typescript\ninterface Cache<K, V> {\n  get(key: K): V | null;\n  put(key: K, value: V): void;\n  remove(key: K): void;\n}\n\nclass LRUCache<K, V> implements Cache<K, V> {\n  private capacity: number;\n  private cache: Map<K, V>;\n  private usage: Map<K, number>;\n  private time: number = 0;\n\n  constructor(capacity: number) {\n    this.capacity = capacity;\n    this.cache = new Map();\n    this.usage = new Map();\n  }\n\n  get(key: K): V | null {\n    const value = this.cache.get(key);\n    if (value !== undefined) {\n      this.usage.set(key, ++this.time);\n      return value;\n    }\n    return null;\n  }\n\n  put(key: K, value: V): void {\n    if (this.cache.size >= this.capacity && !this.cache.has(key)) {\n      // Find least recently used item\n      let lruKey = this.findLRU();\n      this.cache.delete(lruKey);\n      this.usage.delete(lruKey);\n    }\n\n    this.cache.set(key, value);\n    this.usage.set(key, ++this.time);\n  }\n\n  remove(key: K): void {\n    this.cache.delete(key);\n    this.usage.delete(key);\n  }\n\n  private findLRU(): K {\n    let minTime = Infinity;\n    let lruKey: K = null!;\n    \n    this.usage.forEach((time, key) => {\n      if (time < minTime) {\n        minTime = time;\n        lruKey = key;\n      }\n    });\n    \n    return lruKey;\n  }\n}\n```\n\n## Message Queue\n\n```typescript\ninterface Message {\n  id: string;\n  payload: any;\n  timestamp: number;\n}\n\nclass MessageQueue {\n  private queue: Message[] = [];\n  private consumers: Set<(message: Message) => void> = new Set();\n\n  publish(message: Message): void {\n    this.queue.push(message);\n    this.notifyConsumers(message);\n  }\n\n  subscribe(callback: (message: Message) => void): () => void {\n    this.consumers.add(callback);\n    return () => this.consumers.delete(callback);\n  }\n\n  private notifyConsumers(message: Message): void {\n    this.consumers.forEach(callback => {\n      try {\n        callback(message);\n      } catch (error) {\n        console.error('Error processing message:', error);\n      }\n    });\n  }\n}\n```\n\n## Rate Limiting\n\n```typescript\nclass TokenBucket {\n  private tokens: number;\n  private lastRefill: number;\n  private readonly capacity: number;\n  private readonly refillRate: number;\n\n  constructor(capacity: number, refillRate: number) {\n    this.capacity = capacity;\n    this.refillRate = refillRate;\n    this.tokens = capacity;\n    this.lastRefill = Date.now();\n  }\n\n  consume(tokens: number = 1): boolean {\n    this.refill();\n\n    if (this.tokens >= tokens) {\n      this.tokens -= tokens;\n      return true;\n    }\n\n    return false;\n  }\n\n  private refill(): void {\n    const now = Date.now();\n    const timePassed = now - this.lastRefill;\n    const tokensToAdd = (timePassed * this.refillRate) / 1000;\n\n    this.tokens = Math.min(this.capacity, this.tokens + tokensToAdd);\n    this.lastRefill = now;\n  }\n}\n```\n\n## Service Discovery\n\n```typescript\ninterface ServiceRegistry {\n  register(service: Service): void;\n  unregister(serviceId: string): void;\n  discover(serviceName: string): Service[];\n}\n\nclass EtcdServiceRegistry implements ServiceRegistry {\n  private services: Map<string, Service[]> = new Map();\n\n  register(service: Service): void {\n    const services = this.services.get(service.name) || [];\n    services.push(service);\n    this.services.set(service.name, services);\n  }\n\n  unregister(serviceId: string): void {\n    this.services.forEach((services, name) => {\n      const filtered = services.filter(s => s.id !== serviceId);\n      if (filtered.length > 0) {\n        this.services.set(name, filtered);\n      } else {\n        this.services.delete(name);\n      }\n    });\n  }\n\n  discover(serviceName: string): Service[] {\n    return this.services.get(serviceName) || [];\n  }\n}\n```\n\n## Circuit Breaker\n\n```typescript\nenum CircuitState {\n  CLOSED,\n  OPEN,\n  HALF_OPEN\n}\n\nclass CircuitBreaker {\n  private state: CircuitState = CircuitState.CLOSED;\n  private failures: number = 0;\n  private lastFailure: number = 0;\n  private readonly threshold: number;\n  private readonly timeout: number;\n\n  constructor(threshold: number = 5, timeout: number = 60000) {\n    this.threshold = threshold;\n    this.timeout = timeout;\n  }\n\n  async execute<T>(\n    action: () => Promise<T>,\n    fallback: () => Promise<T>\n  ): Promise<T> {\n    if (this.state === CircuitState.OPEN) {\n      if (Date.now() - this.lastFailure >= this.timeout) {\n        this.state = CircuitState.HALF_OPEN;\n      } else {\n        return fallback();\n      }\n    }\n\n    try {\n      const result = await action();\n      if (this.state === CircuitState.HALF_OPEN) {\n        this.state = CircuitState.CLOSED;\n        this.failures = 0;\n      }\n      return result;\n    } catch (error) {\n      this.failures++;\n      this.lastFailure = Date.now();\n\n      if (this.failures >= this.threshold) {\n        this.state = CircuitState.OPEN;\n      }\n\n      return fallback();\n    }\n  }\n}\n```\n\n## Best Practices\n\n1. Scalability\n   - Horizontal scaling\n   - Database sharding\n   - Caching strategies\n   - Load balancing\n\n2. Reliability\n   - Circuit breakers\n   - Retry mechanisms\n   - Fallback strategies\n   - Error handling\n\n3. Maintainability\n   - Service discovery\n   - Configuration management\n   - Monitoring and logging\n   - Documentation\n\n4. Performance\n   - Caching\n   - Connection pooling\n   - Asynchronous processing\n   - Resource optimization\n\n## Conclusion\n\nEffective system design requires careful consideration of scalability, reliability, and maintainability. These patterns and principles provide a foundation for building robust systems.\n",
            "url": "https://www.dibakarmitra.com/notes/system-design-principles",
            "title": "System Design Principles and Best Practices",
            "date_modified": "2024-01-15T00:00:00.000Z",
            "author": {
                "name": "Dibakar Mitra",
                "url": "https://www.dibakarmitra.com"
            },
            "tags": [
                "System Design",
                "Architecture",
                "Scalability",
                "Backend"
            ]
        },
        {
            "id": "https://www.dibakarmitra.com/notes/api-design-patterns",
            "content_html": "\n# API Design Patterns and Best Practices\n\nDesigning good APIs is crucial for building maintainable and scalable applications. Let's explore best practices and patterns.\n\n## RESTful API Design\n\n### Resource Modeling\n\n```typescript\n// User Resource\ninterface User {\n  id: string;\n  name: string;\n  email: string;\n  role: UserRole;\n  createdAt: Date;\n  updatedAt: Date;\n}\n\n// API Endpoints\nclass UserController {\n  // GET /users\n  async listUsers(\n    page: number = 1,\n    limit: number = 10,\n    sort?: string\n  ): Promise<PaginatedResponse<User>> {\n    // Implementation\n  }\n\n  // GET /users/:id\n  async getUser(id: string): Promise<User> {\n    // Implementation\n  }\n\n  // POST /users\n  async createUser(data: CreateUserDTO): Promise<User> {\n    // Implementation\n  }\n\n  // PATCH /users/:id\n  async updateUser(id: string, data: UpdateUserDTO): Promise<User> {\n    // Implementation\n  }\n\n  // DELETE /users/:id\n  async deleteUser(id: string): Promise<void> {\n    // Implementation\n  }\n}\n```\n\n## Response Handling\n\n```typescript\ninterface ApiResponse<T> {\n  data: T;\n  meta?: {\n    page?: number;\n    limit?: number;\n    total?: number;\n  };\n  links?: {\n    self: string;\n    next?: string;\n    prev?: string;\n  };\n}\n\ninterface ApiError {\n  code: string;\n  message: string;\n  details?: Record<string, any>;\n}\n\n// Example Response Handler\nclass ResponseHandler {\n  static success<T>(data: T, meta?: any): ApiResponse<T> {\n    return {\n      data,\n      meta,\n      links: {\n        self: getCurrentUrl()\n      }\n    };\n  }\n\n  static error(error: Error): ApiError {\n    return {\n      code: error.name,\n      message: error.message,\n      details: error instanceof ApiError ? error.details : undefined\n    };\n  }\n}\n```\n\n## Validation\n\n```typescript\nimport { z } from 'zod';\n\n// Request Validation Schema\nconst CreateUserSchema = z.object({\n  name: z.string().min(2).max(100),\n  email: z.string().email(),\n  password: z.string().min(8).regex(/[A-Z]/).regex(/[0-9]/),\n  role: z.enum(['user', 'admin'])\n});\n\n// Middleware\nfunction validateRequest(schema: z.Schema) {\n  return async (req: Request, res: Response, next: NextFunction) => {\n    try {\n      req.body = await schema.parseAsync(req.body);\n      next();\n    } catch (error) {\n      if (error instanceof z.ZodError) {\n        res.status(400).json({\n          code: 'VALIDATION_ERROR',\n          message: 'Invalid request data',\n          details: error.errors\n        });\n      } else {\n        next(error);\n      }\n    }\n  };\n}\n```\n\n## Rate Limiting\n\n```typescript\nimport rateLimit from 'express-rate-limit';\nimport Redis from 'ioredis';\n\nclass RateLimiter {\n  private redis: Redis;\n  private prefix: string;\n\n  constructor(redisUrl: string, prefix: string = 'ratelimit:') {\n    this.redis = new Redis(redisUrl);\n    this.prefix = prefix;\n  }\n\n  createLimiter(options: {\n    windowMs: number;\n    max: number;\n    keyGenerator?: (req: Request) => string;\n  }) {\n    return rateLimit({\n      store: {\n        increment: async (key: string) => {\n          const redisKey = this.prefix + key;\n          const multi = this.redis.multi();\n          \n          multi.incr(redisKey);\n          multi.pexpire(redisKey, options.windowMs);\n          \n          const [count] = await multi.exec();\n          return count?.[1] as number;\n        },\n        decrement: async (key: string) => {\n          await this.redis.decr(this.prefix + key);\n        },\n        resetKey: async (key: string) => {\n          await this.redis.del(this.prefix + key);\n        }\n      },\n      ...options\n    });\n  }\n}\n```\n\n## Versioning\n\n```typescript\n// Version through URL\n// /api/v1/users\n\n// Version through Accept header\napp.use((req, res, next) => {\n  const accept = req.get('Accept');\n  if (accept?.includes('version=1')) {\n    req.apiVersion = 1;\n  } else if (accept?.includes('version=2')) {\n    req.apiVersion = 2;\n  } else {\n    req.apiVersion = 1; // default version\n  }\n  next();\n});\n\n// Version-specific controllers\nclass UserControllerV1 {\n  // V1 implementations\n}\n\nclass UserControllerV2 extends UserControllerV1 {\n  // V2 implementations with changes\n  async listUsers(page: number = 1, limit: number = 10): Promise<User[]> {\n    // New implementation\n    return super.listUsers(page, limit);\n  }\n}\n```\n\n## Documentation\n\n```typescript\n/**\n * @api {post} /users Create User\n * @apiVersion 1.0.0\n * @apiName CreateUser\n * @apiGroup Users\n *\n * @apiParam {String} name User's full name\n * @apiParam {String} email User's email\n * @apiParam {String} password User's password\n * @apiParam {String=\"user\",\"admin\"} role User's role\n *\n * @apiSuccess {String} id User's unique ID\n * @apiSuccess {String} name User's name\n * @apiSuccess {String} email User's email\n * @apiSuccess {String} role User's role\n * @apiSuccess {Date} createdAt Creation timestamp\n *\n * @apiError {String} code Error code\n * @apiError {String} message Error message\n * @apiError {Object} details Validation details\n */\nasync createUser(req: Request, res: Response) {\n  // Implementation\n}\n```\n\n## GraphQL API Design\n\n```typescript\nimport { gql } from 'apollo-server';\n\nconst typeDefs = gql`\n  type User {\n    id: ID!\n    name: String!\n    email: String!\n    posts: [Post!]!\n    profile: Profile\n  }\n\n  type Post {\n    id: ID!\n    title: String!\n    content: String!\n    author: User!\n    comments: [Comment!]!\n  }\n\n  input CreateUserInput {\n    name: String!\n    email: String!\n    password: String!\n  }\n\n  type Mutation {\n    createUser(input: CreateUserInput!): User!\n    updateUser(id: ID!, input: UpdateUserInput!): User!\n    deleteUser(id: ID!): Boolean!\n  }\n\n  type Query {\n    users(\n      page: Int = 1\n      limit: Int = 10\n      sort: String\n    ): UserConnection!\n    user(id: ID!): User\n  }\n`;\n\nconst resolvers = {\n  Query: {\n    users: async (_, { page, limit, sort }, context) => {\n      // Implementation with pagination\n    },\n    user: async (_, { id }, context) => {\n      // Implementation\n    }\n  },\n  Mutation: {\n    createUser: async (_, { input }, context) => {\n      // Implementation\n    }\n  }\n};\n```\n\n## Best Practices\n\n1. Resource Design\n   - Use nouns for resources\n   - Keep URLs consistent\n   - Use proper HTTP methods\n   - Implement HATEOAS\n\n2. Security\n   - Use HTTPS\n   - Implement authentication\n   - Rate limiting\n   - Input validation\n\n3. Performance\n   - Implement caching\n   - Use pagination\n   - Support filtering\n   - Enable compression\n\n4. Documentation\n   - OpenAPI/Swagger\n   - Clear examples\n   - Error documentation\n   - Version documentation\n\n## Conclusion\n\nGood API design focuses on developer experience, maintainability, and scalability. Following these patterns and practices helps create robust and user-friendly APIs.\n",
            "url": "https://www.dibakarmitra.com/notes/api-design-patterns",
            "title": "API Design Patterns and Best Practices",
            "date_modified": "2024-01-10T00:00:00.000Z",
            "author": {
                "name": "Dibakar Mitra",
                "url": "https://www.dibakarmitra.com"
            },
            "tags": [
                "API Design",
                "REST",
                "GraphQL",
                "Web Development"
            ]
        },
        {
            "id": "https://www.dibakarmitra.com/notes/database-design-patterns",
            "content_html": "\n# Database Design Patterns and Best Practices\n\nEffective database design is crucial for application performance and scalability. Let's explore key patterns and practices.\n\n## Schema Design\n\n### Relational Database Schema\n\n```sql\n-- Users Table\nCREATE TABLE users (\n    id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),\n    email VARCHAR(255) UNIQUE NOT NULL CHECK (email ~* '^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,}$'),\n    password_hash VARCHAR(255) NOT NULL,\n    full_name VARCHAR(100) NOT NULL,\n    created_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP,\n    updated_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP\n);\n\n-- Posts Table\nCREATE TABLE posts (\n    id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),\n    user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,\n    title VARCHAR(200) NOT NULL,\n    content TEXT NOT NULL,\n    status VARCHAR(20) DEFAULT 'draft' CHECK (status IN ('draft', 'published', 'archived')),\n    published_at TIMESTAMP WITH TIME ZONE,\n    created_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP,\n    updated_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP\n);\n\n-- Tags Table\nCREATE TABLE tags (\n    id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),\n    name VARCHAR(50) UNIQUE NOT NULL,\n    created_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP\n);\n\n-- Posts Tags Junction Table\nCREATE TABLE posts_tags (\n    post_id UUID REFERENCES posts(id) ON DELETE CASCADE,\n    tag_id UUID REFERENCES tags(id) ON DELETE CASCADE,\n    PRIMARY KEY (post_id, tag_id)\n);\n\n-- Indexes\nCREATE INDEX idx_users_email ON users(email);\nCREATE INDEX idx_posts_user_id ON posts(user_id);\nCREATE INDEX idx_posts_status ON posts(status);\nCREATE INDEX idx_posts_published_at ON posts(published_at);\n```\n\n## NoSQL Schema Design\n\n### MongoDB Schema\n\n```typescript\nimport { ObjectId } from 'mongodb';\n\ninterface User {\n  _id: ObjectId;\n  email: string;\n  passwordHash: string;\n  fullName: string;\n  profile: {\n    bio: string;\n    avatar: string;\n    socialLinks: {\n      platform: string;\n      url: string;\n    }[];\n  };\n  createdAt: Date;\n  updatedAt: Date;\n}\n\n// MongoDB Schema Validation\ndb.createCollection(\"users\", {\n   validator: {\n      $jsonSchema: {\n         bsonType: \"object\",\n         required: [\"email\", \"passwordHash\", \"fullName\"],\n         properties: {\n            email: {\n               bsonType: \"string\",\n               pattern: \"^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\\\.[A-Za-z]{2,}$\"\n            }\n         }\n      }\n   }\n});\n\ninterface Post {\n  _id: ObjectId;\n  userId: ObjectId;\n  title: string;\n  content: string;\n  status: 'draft' | 'published' | 'archived';\n  tags: string[];\n  comments: {\n    userId: ObjectId;\n    content: string;\n    createdAt: Date;\n  }[];\n  metadata: {\n    views: number;\n    likes: number;\n    shares: number;\n  };\n  publishedAt?: Date;\n  createdAt: Date;\n  updatedAt: Date;\n}\n```\n\n## Query Optimization\n\n### SQL Query Optimization\n\n```sql\n-- Using Indexes Effectively\nEXPLAIN ANALYZE\nSELECT p.*, u.full_name as author_name\nFROM posts p\nJOIN users u ON p.user_id = u.id\nWHERE p.status = 'published'\n  AND p.published_at >= NOW() - INTERVAL '7 days'\nORDER BY p.published_at DESC\nLIMIT 10;\n\n-- Optimized Query with Materialized View\nCREATE MATERIALIZED VIEW recent_posts AS\nSELECT \n    p.*,\n    u.full_name as author_name,\n    COUNT(c.id) as comment_count\nFROM posts p\nJOIN users u ON p.user_id = u.id\nLEFT JOIN comments c ON p.id = c.post_id\nWHERE p.status = 'published'\nGROUP BY p.id, u.full_name\nORDER BY p.published_at DESC;\n\n-- Refresh Materialized View\nREFRESH MATERIALIZED VIEW recent_posts;\n```\n\n## Database Migrations\n\n```typescript\nimport { MigrationInterface, QueryRunner } from 'typeorm';\n\nexport class AddUserProfileTable1641234567890 implements MigrationInterface {\n  public async up(queryRunner: QueryRunner): Promise<void> {\n    await queryRunner.query(`\n      CREATE TABLE user_profiles (\n        id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),\n        user_id UUID NOT NULL UNIQUE REFERENCES users(id) ON DELETE CASCADE,\n        bio TEXT,\n        avatar_url VARCHAR(255),\n        location VARCHAR(100),\n        created_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP,\n        updated_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP\n      );\n\n      CREATE INDEX idx_user_profiles_user_id ON user_profiles(user_id);\n    `);\n  }\n\n  public async down(queryRunner: QueryRunner): Promise<void> {\n    await queryRunner.query(`\n      DROP TABLE user_profiles;\n    `);\n  }\n}\n```\n\n## Connection Pooling\n\n```typescript\nimport { Pool, QueryResult } from 'pg';\n\ninterface DatabaseConfig {\n  user: string;\n  host: string;\n  database: string;\n  password: string;\n  port: number;\n  max: number;\n  idleTimeoutMillis: number;\n  connectionTimeoutMillis: number;\n}\n\nconst config: DatabaseConfig = {\n  user: process.env.DB_USER,\n  host: process.env.DB_HOST,\n  database: process.env.DB_NAME,\n  password: process.env.DB_PASSWORD,\n  port: parseInt(process.env.DB_PORT || '5432'),\n  max: 20,\n  idleTimeoutMillis: 30000,\n  connectionTimeoutMillis: 2000,\n};\n\nconst pool = new Pool(config);\n\n// Error handling\npool.on('error', (err: Error) => {\n  console.error('Unexpected error on idle client', err);\n  process.exit(-1);\n});\n\ninterface Post {\n  id: string;\n  user_id: string;\n  title: string;\n  content: string;\n  status: 'draft' | 'published' | 'archived';\n  published_at: Date | null;\n  created_at: Date;\n  updated_at: Date;\n}\n\nasync function getUserPosts(userId: string): Promise<Post[]> {\n  const client = await pool.connect();\n  try {\n    const result: QueryResult<Post> = await client.query(\n      'SELECT * FROM posts WHERE user_id = $1',\n      [userId]\n    );\n    return result.rows;\n  } catch (error) {\n    console.error('Error fetching user posts:', error);\n    throw error;\n  } finally {\n    client.release();\n  }\n}\n```\n\n## Caching Strategies\n\n```typescript\nimport Redis from 'ioredis';\n\nclass CacheManager {\n  private redis: Redis;\n  private defaultTTL: number;\n\n  constructor(redisUrl: string, defaultTTL: number = 3600) {\n    this.redis = new Redis(redisUrl);\n    this.defaultTTL = defaultTTL;\n  }\n\n  async get<T>(key: string): Promise<T | null> {\n    const data = await this.redis.get(key);\n    return data ? JSON.parse(data) : null;\n  }\n\n  async set<T>(\n    key: string,\n    value: T,\n    ttl: number = this.defaultTTL\n  ): Promise<void> {\n    await this.redis.set(\n      key,\n      JSON.stringify(value),\n      'EX',\n      ttl\n    );\n  }\n\n  async invalidate(pattern: string): Promise<void> {\n    const keys = await this.redis.keys(pattern);\n    if (keys.length > 0) {\n      await this.redis.del(...keys);\n    }\n  }\n}\n\n// Usage example\nconst cache = new CacheManager('redis://localhost:6379');\n\nasync function getCachedUserPosts(userId: string) {\n  const cacheKey = `user:${userId}:posts`;\n  \n  // Try cache first\n  const cached = await cache.get(cacheKey);\n  if (cached) return cached;\n\n  // If not in cache, get from database\n  const posts = await getUserPosts(userId);\n  \n  // Store in cache\n  await cache.set(cacheKey, posts);\n  \n  return posts;\n}\n```\n\n## Data Partitioning\n\n```sql\n-- Create Partition Table\nCREATE TABLE events (\n    id UUID NOT NULL,\n    user_id UUID NOT NULL,\n    event_type VARCHAR(50) NOT NULL,\n    event_data JSONB,\n    created_at TIMESTAMP WITH TIME ZONE NOT NULL\n) PARTITION BY RANGE (created_at);\n\n-- Create Partitions\nCREATE TABLE events_2024_q1 PARTITION OF events\n    FOR VALUES FROM ('2024-01-01') TO ('2024-04-01');\n\nCREATE TABLE events_2024_q2 PARTITION OF events\n    FOR VALUES FROM ('2024-04-01') TO ('2024-07-01');\n\n-- Add Indexes to Parent Table\nCREATE INDEX idx_events_user_id ON events(user_id);\nCREATE INDEX idx_events_event_type ON events(event_type);\nCREATE INDEX idx_events_created_at ON events(created_at);\n```\n\n## Best Practices\n\n1. Schema Design\n   - Normalize appropriately\n   - Use appropriate data types\n   - Implement constraints\n   - Plan for scaling\n\n2. Performance\n   - Index strategically\n   - Optimize queries\n   - Use connection pooling\n   - Implement caching\n\n3. Data Integrity\n   - Use transactions\n   - Implement constraints\n   - Regular backups\n   - Data validation\n\n4. Security\n   - Access control\n   - Encryption at rest\n   - Secure connections\n   - Regular audits\n\n## Conclusion\n\nGood database design requires careful consideration of data structure, performance, and scalability. These patterns and practices help create robust and efficient database systems.\n",
            "url": "https://www.dibakarmitra.com/notes/database-design-patterns",
            "title": "Database Design Patterns and Best Practices",
            "date_modified": "2024-01-05T00:00:00.000Z",
            "author": {
                "name": "Dibakar Mitra",
                "url": "https://www.dibakarmitra.com"
            },
            "tags": [
                "Database",
                "SQL",
                "NoSQL",
                "Data Modeling"
            ]
        },
        {
            "id": "https://www.dibakarmitra.com/notes/frontend-performance-optimization",
            "content_html": "\n# Frontend Performance Optimization: A Comprehensive Guide\n\nPerformance optimization is crucial for delivering excellent user experiences. This guide explores advanced techniques and best practices for optimizing frontend applications.\n\n## Core Web Vitals\n\n### Largest Contentful Paint (LCP)\n```javascript\n// Measure LCP\nnew PerformanceObserver((entryList) => {\n  for (const entry of entryList.getEntries()) {\n    console.log('LCP:', entry.startTime);\n    console.log('Element:', entry.element);\n  }\n}).observe({ entryTypes: ['largest-contentful-paint'] });\n```\n\n### First Input Delay (FID)\n```javascript\n// Measure FID\nnew PerformanceObserver((entryList) => {\n  for (const entry of entryList.getEntries()) {\n    const delay = entry.processingStart - entry.startTime;\n    console.log('FID:', delay);\n  }\n}).observe({ entryTypes: ['first-input'] });\n```\n\n## Image Optimization\n\n### Next.js Image Component\n```jsx\nimport Image from 'next/image';\n\nfunction OptimizedImage() {\n  return (\n    <Image\n      src=\"/large-image.jpg\"\n      alt=\"Optimized image\"\n      width={800}\n      height={600}\n      placeholder=\"blur\"\n      blurDataURL=\"data:image/jpeg;base64,...\"\n      priority={true}\n    />\n  );\n}\n```\n\n### Lazy Loading Implementation\n```javascript\n// Intersection Observer for lazy loading\nconst lazyLoadImages = () => {\n  const images = document.querySelectorAll('[data-src]');\n  \n  const imageObserver = new IntersectionObserver((entries) => {\n    entries.forEach(entry => {\n      if (entry.isIntersecting) {\n        const img = entry.target;\n        img.src = img.dataset.src;\n        img.removeAttribute('data-src');\n        imageObserver.unobserve(img);\n      }\n    });\n  });\n\n  images.forEach(img => imageObserver.observe(img));\n};\n```\n\n## Code Splitting\n\n### React.lazy and Suspense\n```jsx\nimport React, { Suspense } from 'react';\n\nconst HeavyComponent = React.lazy(() => import('./HeavyComponent'));\n\nfunction App() {\n  return (\n    <Suspense fallback={<LoadingSpinner />}>\n      <HeavyComponent />\n    </Suspense>\n  );\n}\n```\n\n### Route-Based Splitting\n```javascript\n// Next.js dynamic imports\nimport dynamic from 'next/dynamic';\n\nconst DynamicComponent = dynamic(() => import('../components/Heavy'), {\n  loading: () => <p>Loading...</p>,\n  ssr: false\n});\n```\n\n## Bundle Optimization\n\n### Webpack Configuration\n```javascript\n// webpack.config.js\nmodule.exports = {\n  optimization: {\n    splitChunks: {\n      chunks: 'all',\n      maxInitialRequests: 25,\n      minSize: 20000,\n      cacheGroups: {\n        vendor: {\n          test: /[\\\\/]node_modules[\\\\/]/,\n          name(module) {\n            const packageName = module.context.match(\n              /[\\\\/]node_modules[\\\\/](.*?)([\\\\/]|$)/\n            )[1];\n            return `vendor.${packageName.replace('@', '')}`;\n          },\n        },\n      },\n    },\n  },\n};\n```\n\n## State Management Optimization\n\n### React Performance Hooks\n```jsx\nimport { useMemo, useCallback } from 'react';\n\nfunction ExpensiveComponent({ data, onUpdate }) {\n  // Memoize expensive calculations\n  const processedData = useMemo(() => {\n    return data.map(item => expensiveOperation(item));\n  }, [data]);\n\n  // Memoize callbacks\n  const handleClick = useCallback(() => {\n    onUpdate(processedData);\n  }, [processedData, onUpdate]);\n\n  return (\n    <div onClick={handleClick}>\n      {processedData.map(item => (\n        <Item key={item.id} {...item} />\n      ))}\n    </div>\n  );\n}\n```\n\n## CSS Performance\n\n### Critical CSS\n```javascript\n// Extract critical CSS\nconst critical = require('critical');\n\ncritical.generate({\n  base: 'dist/',\n  src: 'index.html',\n  target: {\n    css: 'critical.css',\n    html: 'index-critical.html',\n  },\n  width: 1300,\n  height: 900,\n});\n```\n\n### CSS-in-JS Optimization\n```jsx\n// Styled-components with dynamic props optimization\nconst StyledButton = styled.button`\n  background: ${props => props.primary ? 'blue' : 'gray'};\n  color: white;\n  \n  /* Use CSS variables for dynamic values */\n  --button-padding: ${props => props.size === 'large' ? '1rem' : '0.5rem'};\n  padding: var(--button-padding);\n`;\n```\n\n## Memory Management\n\n### Memory Leak Prevention\n```javascript\nclass Component extends React.Component {\n  componentDidMount() {\n    this.interval = setInterval(this.tick, 1000);\n    window.addEventListener('resize', this.handleResize);\n  }\n\n  componentWillUnmount() {\n    // Clean up subscriptions and listeners\n    clearInterval(this.interval);\n    window.removeEventListener('resize', this.handleResize);\n  }\n}\n```\n\n## Network Optimization\n\n### Service Worker Implementation\n```javascript\n// service-worker.js\nconst CACHE_NAME = 'v1';\nconst urlsToCache = [\n  '/',\n  '/styles/main.css',\n  '/scripts/main.js'\n];\n\nself.addEventListener('install', event => {\n  event.waitUntil(\n    caches.open(CACHE_NAME)\n      .then(cache => cache.addAll(urlsToCache))\n  );\n});\n\nself.addEventListener('fetch', event => {\n  event.respondWith(\n    caches.match(event.request)\n      .then(response => response || fetch(event.request))\n  );\n});\n```\n\n## Virtual DOM Optimization\n\n### React Rendering Optimization\n```jsx\n// Use React.memo for component memoization\nconst MemoizedComponent = React.memo(function MyComponent(props) {\n  return (\n    <div>\n      <ExpensiveTree {...props} />\n    </div>\n  );\n}, (prevProps, nextProps) => {\n  return prevProps.id === nextProps.id;\n});\n```\n\n## Performance Monitoring\n\n### Web Vitals Tracking\n```javascript\nimport { getCLS, getFID, getLCP } from 'web-vitals';\n\nfunction sendToAnalytics({ name, delta, id }) {\n  // Send metrics to analytics\n  gtag('event', name, {\n    event_category: 'Web Vitals',\n    event_label: id,\n    value: Math.round(name === 'CLS' ? delta * 1000 : delta),\n    non_interaction: true,\n  });\n}\n\ngetCLS(sendToAnalytics);\ngetFID(sendToAnalytics);\ngetLCP(sendToAnalytics);\n```\n\n## Best Practices\n\n### 1. Loading Performance\n- Implement progressive loading\n- Use resource hints\n- Optimize critical rendering path\n\n### 2. Runtime Performance\n- Avoid layout thrashing\n- Use requestAnimationFrame\n- Debounce and throttle events\n\n### 3. Memory Management\n- Clean up event listeners\n- Use WeakMap for caching\n- Monitor memory leaks\n\n## Common Pitfalls\n\n1. **Render Blocking Resources**\n   - Unoptimized images\n   - Render-blocking CSS/JS\n   - Heavy third-party scripts\n\n2. **State Management Issues**\n   - Unnecessary re-renders\n   - Deep component trees\n   - Prop drilling\n\n## Tools and Resources\n\n1. **Performance Measurement**\n   - Lighthouse\n   - Chrome DevTools\n   - WebPageTest\n\n2. **Monitoring Tools**\n   - Google Analytics\n   - New Relic\n   - Sentry\n\n## Conclusion\n\nFrontend performance optimization is an ongoing process that requires attention to multiple aspects of web development. By implementing these techniques and following best practices, you can significantly improve your application's performance and user experience.\n\n## Resources\n\n1. Web Vitals Documentation\n2. Chrome DevTools Documentation\n3. React Performance Documentation\n4. MDN Performance Guide\n5. Google PageSpeed Insights",
            "url": "https://www.dibakarmitra.com/notes/frontend-performance-optimization",
            "title": "Frontend Performance Optimization: A Comprehensive Guide",
            "summary": "Learn advanced techniques for optimizing frontend performance in modern web applications",
            "date_modified": "2023-12-28T00:00:00.000Z",
            "author": {
                "name": "Dibakar Mitra",
                "url": "https://www.dibakarmitra.com"
            },
            "tags": [
                "Performance",
                "Web Development",
                "JavaScript",
                "React"
            ]
        },
        {
            "id": "https://www.dibakarmitra.com/notes/cloud-native-architecture",
            "content_html": "\n# Cloud Native Architecture: Building Modern Scalable Systems\n\nCloud native architecture represents a modern approach to building and running applications that fully exploit the advantages of the cloud computing model. This comprehensive guide explores the principles, patterns, and practices that define cloud native systems.\n\n## Core Principles of Cloud Native Architecture\n\n### 1. Containerization\n```yaml\n# Example Dockerfile\nFROM node:18-alpine\nWORKDIR /app\nCOPY package*.json ./\nRUN npm install\nCOPY . .\nEXPOSE 3000\nCMD [\"npm\", \"start\"]\n```\n\n### 2. Microservices\n- Service independence\n- Loose coupling\n- API-first design\n- Domain-driven design\n\n### 3. DevOps Culture\n- Continuous Integration\n- Continuous Deployment\n- Infrastructure as Code\n- Automated testing\n\n## Kubernetes: The Foundation\n\n### Basic Deployment\n```yaml\napiVersion: apps/v1\nkind: Deployment\nmetadata:\n  name: myapp\nspec:\n  replicas: 3\n  selector:\n    matchLabels:\n      app: myapp\n  template:\n    metadata:\n      labels:\n        app: myapp\n    spec:\n      containers:\n      - name: myapp\n        image: myapp:1.0.0\n        ports:\n        - containerPort: 8080\n```\n\n### Service Definition\n```yaml\napiVersion: v1\nkind: Service\nmetadata:\n  name: myapp-service\nspec:\n  selector:\n    app: myapp\n  ports:\n  - port: 80\n    targetPort: 8080\n  type: LoadBalancer\n```\n\n## Infrastructure as Code (IaC)\n\n### Terraform Example\n```hcl\nprovider \"aws\" {\n  region = \"us-west-2\"\n}\n\nresource \"aws_eks_cluster\" \"main\" {\n  name     = \"main-cluster\"\n  role_arn = aws_iam_role.eks_cluster.arn\n\n  vpc_config {\n    subnet_ids = var.subnet_ids\n  }\n}\n```\n\n## Service Mesh Architecture\n\n### Istio Configuration\n```yaml\napiVersion: networking.istio.io/v1alpha3\nkind: VirtualService\nmetadata:\n  name: myapp-route\nspec:\n  hosts:\n  - myapp.example.com\n  http:\n  - route:\n    - destination:\n        host: myapp-service\n        subset: v1\n      weight: 90\n    - destination:\n        host: myapp-service\n        subset: v2\n      weight: 10\n```\n\n## Observability\n\n### 1. Logging\n```yaml\n# Elasticsearch Fluentd Kibana (EFK) Stack\napiVersion: v1\nkind: ConfigMap\nmetadata:\n  name: fluentd-config\ndata:\n  fluent.conf: |\n    <source>\n      @type tail\n      path /var/log/containers/*.log\n      pos_file /var/log/fluentd-containers.log.pos\n      tag kubernetes.*\n    </source>\n```\n\n### 2. Monitoring\n```yaml\n# Prometheus configuration\napiVersion: monitoring.coreos.com/v1\nkind: ServiceMonitor\nmetadata:\n  name: app-monitor\nspec:\n  selector:\n    matchLabels:\n      app: myapp\n  endpoints:\n  - port: metrics\n```\n\n### 3. Tracing\n```javascript\n// OpenTelemetry implementation\nconst tracer = opentelemetry.trace.getTracer('my-service');\n\nasync function handleRequest(req, res) {\n  const span = tracer.startSpan('process-request');\n  try {\n    // Process request\n    span.setStatus({ code: SpanStatusCode.OK });\n  } catch (error) {\n    span.setStatus({ code: SpanStatusCode.ERROR, message: error.message });\n  } finally {\n    span.end();\n  }\n}\n```\n\n## Scalability Patterns\n\n### 1. Horizontal Pod Autoscaling\n```yaml\napiVersion: autoscaling/v2\nkind: HorizontalPodAutoscaler\nmetadata:\n  name: myapp-hpa\nspec:\n  scaleTargetRef:\n    apiVersion: apps/v1\n    kind: Deployment\n    name: myapp\n  minReplicas: 2\n  maxReplicas: 10\n  metrics:\n  - type: Resource\n    resource:\n      name: cpu\n      target:\n        type: Utilization\n        averageUtilization: 80\n```\n\n### 2. Event-Driven Architecture\n```javascript\n// Event handler using CloudEvents\nconst cloudEvent = {\n  specversion: \"1.0\",\n  type: \"com.example.order.created\",\n  source: \"/orders\",\n  id: \"123-456\",\n  data: {\n    orderId: \"12345\",\n    customer: \"John Doe\"\n  }\n};\n```\n\n## Security Best Practices\n\n### 1. Pod Security Policies\n```yaml\napiVersion: policy/v1beta1\nkind: PodSecurityPolicy\nmetadata:\n  name: restricted\nspec:\n  privileged: false\n  seLinux:\n    rule: RunAsAny\n  runAsUser:\n    rule: MustRunAsNonRoot\n  fsGroup:\n    rule: RunAsAny\n```\n\n### 2. Network Policies\n```yaml\napiVersion: networking.k8s.io/v1\nkind: NetworkPolicy\nmetadata:\n  name: api-allow\nspec:\n  podSelector:\n    matchLabels:\n      app: api\n  ingress:\n  - from:\n    - podSelector:\n        matchLabels:\n          role: frontend\n```\n\n## Disaster Recovery\n\n### 1. Backup Strategy\n```yaml\n# Velero backup configuration\napiVersion: velero.io/v1\nkind: Backup\nmetadata:\n  name: daily-backup\nspec:\n  includedNamespaces:\n  - production\n  schedule: \"0 1 * * *\"\n  ttl: 720h\n```\n\n### 2. Multi-Region Deployment\n```hcl\n# Terraform multi-region setup\nmodule \"eks_cluster_us_east\" {\n  source = \"./modules/eks\"\n  region = \"us-east-1\"\n}\n\nmodule \"eks_cluster_us_west\" {\n  source = \"./modules/eks\"\n  region = \"us-west-2\"\n}\n```\n\n## Cost Optimization\n\n### 1. Resource Requests and Limits\n```yaml\nresources:\n  requests:\n    memory: \"64Mi\"\n    cpu: \"250m\"\n  limits:\n    memory: \"128Mi\"\n    cpu: \"500m\"\n```\n\n### 2. Spot Instances\n```yaml\napiVersion: apps/v1\nkind: Deployment\nmetadata:\n  name: spot-deployment\nspec:\n  template:\n    spec:\n      nodeSelector:\n        node.kubernetes.io/instance-type: spot\n```\n\n## Best Practices\n\n1. **Infrastructure Management**\n   - Use GitOps principles\n   - Implement Infrastructure as Code\n   - Regular security audits\n\n2. **Application Design**\n   - Follow twelve-factor app methodology\n   - Implement circuit breakers\n   - Use health checks\n\n3. **Operations**\n   - Implement automated rollbacks\n   - Use blue-green deployments\n   - Regular disaster recovery testing\n\n## Common Challenges\n\n1. **Complexity Management**\n   - Service discovery\n   - Configuration management\n   - Dependency management\n\n2. **Performance Optimization**\n   - Resource utilization\n   - Network latency\n   - Cache optimization\n\n## Future Trends\n\n1. **FinOps Integration**\n2. **Edge Computing**\n3. **AI-Driven Operations**\n4. **Zero Trust Security**\n\n## Conclusion\n\nCloud native architecture continues to evolve, offering powerful patterns and practices for building modern, scalable applications. Success in this domain requires a thorough understanding of these concepts and careful consideration of your specific use cases and requirements.\n\n## Resources\n\n1. Cloud Native Computing Foundation\n2. Kubernetes Documentation\n3. Istio Service Mesh\n4. Terraform Documentation\n5. AWS EKS Best Practices",
            "url": "https://www.dibakarmitra.com/notes/cloud-native-architecture",
            "title": "Cloud Native Architecture: Building Modern Scalable Systems",
            "summary": "A comprehensive guide to cloud native architecture principles, patterns, and best practices",
            "date_modified": "2023-12-25T00:00:00.000Z",
            "author": {
                "name": "Dibakar Mitra",
                "url": "https://www.dibakarmitra.com"
            },
            "tags": [
                "Cloud Native",
                "Kubernetes",
                "Microservices",
                "DevOps"
            ]
        },
        {
            "id": "https://www.dibakarmitra.com/notes/ai-ml-web-development",
            "content_html": "\n# AI and Machine Learning in Modern Web Development\n\nArtificial Intelligence (AI) and Machine Learning (ML) are revolutionizing web development, enabling more intelligent, personalized, and interactive web applications. This guide explores how to integrate these technologies into your web projects.\n\n## Client-Side Machine Learning with TensorFlow.js\n\n### Basic Model Implementation\n```javascript\nimport * as tf from '@tensorflow/tfjs';\n\n// Create a simple neural network\nconst model = tf.sequential({\n  layers: [\n    tf.layers.dense({ inputShape: [4], units: 10, activation: 'relu' }),\n    tf.layers.dense({ units: 3, activation: 'softmax' })\n  ]\n});\n\n// Compile the model\nmodel.compile({\n  optimizer: 'adam',\n  loss: 'categoricalCrossentropy',\n  metrics: ['accuracy']\n});\n```\n\n## Common AI/ML Use Cases in Web Development\n\n### 1. Image Recognition\n```javascript\n// Using TensorFlow.js with a pre-trained MobileNet model\nimport * as tf from '@tensorflow/tfjs';\nimport * as mobilenet from '@tensorflow-models/mobilenet';\n\nasync function classifyImage(imageElement) {\n  const model = await mobilenet.load();\n  const predictions = await model.classify(imageElement);\n  return predictions;\n}\n```\n\n### 2. Natural Language Processing\n```javascript\n// Using Transformers.js for text processing\nimport { pipeline } from '@huggingface/transformers';\n\nasync function analyzeSentiment(text) {\n  const sentiment = await pipeline('sentiment-analysis');\n  const result = await sentiment(text);\n  return result;\n}\n```\n\n## AI-Powered Features\n\n### 1. Smart Search Implementation\n```typescript\ninterface SearchResult {\n  content: string;\n  relevanceScore: number;\n}\n\nasync function semanticSearch(query: string): Promise<SearchResult[]> {\n  const embedding = await getEmbedding(query);\n  return searchWithEmbedding(embedding);\n}\n```\n\n### 2. Recommendation Systems\n```javascript\nclass RecommendationEngine {\n  async getUserPreferences(userId) {\n    // Fetch user interaction history\n    const history = await getUserHistory(userId);\n    \n    // Generate recommendations using collaborative filtering\n    return this.collaborativeFilter(history);\n  }\n}\n```\n\n## Performance Optimization\n\n### 1. Model Optimization\n```javascript\nasync function optimizeModel(model) {\n  // Quantize the model to reduce size\n  const quantizedModel = await tf.quantization.quantize(model);\n  \n  // Save the optimized model\n  await quantizedModel.save('indexeddb://optimized-model');\n}\n```\n\n### 2. Lazy Loading\n```javascript\n// Lazy load AI models\nconst loadModel = async () => {\n  if (!globalModel) {\n    globalModel = await tf.loadLayersModel('path/to/model.json');\n  }\n  return globalModel;\n};\n```\n\n## Real-Time Processing\n\n### WebGL Acceleration\n```javascript\ntf.setBackend('webgl').then(() => {\n  console.log('Using WebGL backend');\n});\n```\n\n## Best Practices\n\n### 1. Model Management\n- Version control for models\n- Proper model caching\n- Regular model updates\n\n### 2. Error Handling\n```javascript\nasync function safePredict(input) {\n  try {\n    const model = await loadModel();\n    return await model.predict(input);\n  } catch (error) {\n    console.error('Prediction failed:', error);\n    return fallbackPrediction(input);\n  }\n}\n```\n\n### 3. Privacy Considerations\n- Local processing when possible\n- Data minimization\n- User consent management\n\n## Integration Patterns\n\n### 1. API-First Approach\n```typescript\ninterface AIService {\n  predict(input: any): Promise<Prediction>;\n  train(data: TrainingData): Promise<void>;\n  evaluate(testData: TestData): Promise<Metrics>;\n}\n```\n\n### 2. Hybrid Processing\n```javascript\nclass HybridMLSystem {\n  async process(data) {\n    // Try client-side processing first\n    if (this.canProcessLocally(data)) {\n      return await this.localProcess(data);\n    }\n    // Fall back to server\n    return await this.serverProcess(data);\n  }\n}\n```\n\n## Common Challenges\n\n1. **Model Size**\n   - Implementation of progressive loading\n   - Model compression techniques\n   - Efficient caching strategies\n\n2. **Processing Power**\n   - Hardware acceleration\n   - Batch processing\n   - Optimization techniques\n\n3. **Real-Time Requirements**\n   - WebWorkers implementation\n   - Stream processing\n   - Performance monitoring\n\n## Future Trends\n\n1. **WebGPU Integration**\n2. **Edge ML Processing**\n3. **Federated Learning**\n\n## Development Tools\n\n### 1. Development Environment\n```javascript\nconst devConfig = {\n  enableDebugLogs: true,\n  useTestModel: true,\n  simulateLatency: false\n};\n```\n\n### 2. Testing Framework\n```javascript\ndescribe('AI Model Tests', () => {\n  it('should handle invalid inputs gracefully', async () => {\n    const result = await model.predict(invalidInput);\n    expect(result.isValid).toBe(false);\n  });\n});\n```\n\n## Conclusion\n\nAI and ML are becoming essential components of modern web development, enabling new possibilities for user interaction and automation. By following these best practices and patterns, developers can create powerful, intelligent web applications while maintaining performance and user privacy.\n\n## Resources\n\n1. TensorFlow.js Documentation\n2. Hugging Face Transformers.js\n3. WebGL Performance Guide\n4. AI Model Optimization Techniques\n5. Machine Learning Web Development Patterns",
            "url": "https://www.dibakarmitra.com/notes/ai-ml-web-development",
            "title": "AI and Machine Learning in Modern Web Development",
            "summary": "Exploring the integration of AI and ML technologies in web applications",
            "date_modified": "2023-12-20T00:00:00.000Z",
            "author": {
                "name": "Dibakar Mitra",
                "url": "https://www.dibakarmitra.com"
            },
            "tags": [
                "AI",
                "Machine Learning",
                "Web Development",
                "TensorFlow.js"
            ]
        },
        {
            "id": "https://www.dibakarmitra.com/notes/serverless-architecture",
            "content_html": "\n# Understanding Serverless Architecture: The Future of Cloud Computing\n\nServerless architecture has revolutionized the way we build and deploy applications. Despite its name, serverless computing doesn't mean there are no servers involved – rather, it abstracts away server management from developers, allowing them to focus solely on writing code.\n\n## What is Serverless Architecture?\n\nServerless computing is a cloud computing execution model where the cloud provider automatically manages the infrastructure needed to run your code. You only pay for the actual compute time used, rather than pre-purchased compute capacity.\n\n## Key Benefits\n\n1. **Cost Efficiency**\n   - Pay-per-execution pricing model\n   - No idle server costs\n   - Automatic scaling\n\n2. **Reduced Operational Overhead**\n   - No server management required\n   - Automatic updates and security patches\n   - Built-in high availability\n\n3. **Improved Developer Productivity**\n   - Focus on business logic\n   - Faster time to market\n   - Simplified deployment process\n\n## Popular Serverless Platforms\n\n### AWS Lambda\nThe pioneer in serverless computing, AWS Lambda supports multiple programming languages and seamlessly integrates with other AWS services.\n\n### Azure Functions\nMicrosoft's serverless solution offers excellent .NET integration and competitive pricing.\n\n### Google Cloud Functions\nProvides seamless integration with Google's ecosystem and strong support for event-driven architectures.\n\n## Best Practices\n\n1. **Function Design**\n   - Keep functions focused and small\n   - Implement proper error handling\n   - Use environment variables for configuration\n\n2. **Performance Optimization**\n   - Minimize cold starts\n   - Optimize function dependencies\n   - Implement caching where appropriate\n\n## Real-World Applications\n\n- API backends\n- Data processing pipelines\n- Scheduled tasks and cron jobs\n- Real-time file processing\n- IoT device data handling\n\n## Challenges and Considerations\n\nWhile serverless architecture offers numerous benefits, it's essential to consider potential challenges:\n\n- Cold starts\n- Limited execution duration\n- Vendor lock-in\n- Debugging complexity\n\n## Conclusion\n\nServerless architecture represents a significant shift in cloud computing, offering developers a more efficient and scalable way to build modern applications. While it may not be suitable for every use case, its benefits make it an attractive option for many modern application architectures.\n\n## References\n\n1. AWS Lambda Documentation\n2. Azure Functions Documentation\n3. Cloud Native Computing Foundation\n4. Serverless Framework Documentation",
            "url": "https://www.dibakarmitra.com/notes/serverless-architecture",
            "title": "Understanding Serverless Architecture: The Future of Cloud Computing",
            "summary": "A deep dive into serverless architecture, its benefits, and real-world applications",
            "date_modified": "2023-12-15T00:00:00.000Z",
            "author": {
                "name": "Dibakar Mitra",
                "url": "https://www.dibakarmitra.com"
            },
            "tags": [
                "Cloud Computing",
                "Serverless",
                "AWS Lambda",
                "Azure Functions"
            ]
        },
        {
            "id": "https://www.dibakarmitra.com/notes/microservices-best-practices",
            "content_html": "\n# Microservices Architecture: Best Practices and Design Patterns\n\nMicroservices architecture has become the de facto standard for building large-scale, distributed systems. This post explores essential best practices and patterns that ensure successful microservices implementation.\n\n## Core Principles of Microservices\n\n### 1. Single Responsibility\nEach microservice should focus on a single business capability and have a clear, well-defined purpose.\n\n### 2. Independence\nServices should be loosely coupled and independently deployable, allowing teams to work autonomously.\n\n### 3. Data Ownership\nEach service should own its data and internal logic, exposing functionality through well-defined APIs.\n\n## Essential Best Practices\n\n### 1. API Design\n- Use REST or gRPC for service communication\n- Implement versioning from day one\n- Document APIs using OpenAPI/Swagger\n- Design for backward compatibility\n\n### 2. Data Management\n- Implement database-per-service pattern\n- Use event sourcing for data consistency\n- Implement CQRS where appropriate\n- Handle distributed transactions carefully\n\n### 3. Service Discovery\n- Implement service registry\n- Use health checks\n- Implement circuit breakers\n- Enable dynamic scaling\n\n### 4. Monitoring and Observability\n- Implement distributed tracing\n- Use correlation IDs\n- Set up centralized logging\n- Monitor key metrics\n\n## Common Design Patterns\n\n### 1. API Gateway Pattern\n```text\nClient → API Gateway → Microservices\n```\nBenefits:\n- Single entry point\n- Authentication/Authorization\n- Request routing\n- Response transformation\n\n### 2. Event-Driven Architecture\n- Publish-subscribe pattern\n- Event sourcing\n- CQRS (Command Query Responsibility Segregation)\n\n### 3. Circuit Breaker Pattern\nPrevents cascading failures across services:\n- Closed (normal operation)\n- Open (failure state)\n- Half-open (testing recovery)\n\n## Infrastructure Considerations\n\n### 1. Containerization\n- Use Docker for containerization\n- Implement Kubernetes for orchestration\n- Define resource limits\n- Use multi-stage builds\n\n### 2. CI/CD\n- Automate deployment pipeline\n- Implement blue-green deployments\n- Use feature flags\n- Automate testing\n\n## Common Pitfalls to Avoid\n\n1. **Premature Decomposition**\n   - Don't start with too many services\n   - Begin with a monolith if uncertain\n\n2. **Inappropriate Service Boundaries**\n   - Align with business domains\n   - Consider data ownership\n\n3. **Distributed Monolith**\n   - Avoid tight coupling\n   - Maintain service independence\n\n## Security Best Practices\n\n1. **Authentication/Authorization**\n   - Implement OAuth 2.0/JWT\n   - Use API keys\n   - Implement rate limiting\n\n2. **Network Security**\n   - Use HTTPS everywhere\n   - Implement network policies\n   - Use service mesh for security\n\n## Conclusion\n\nBuilding a successful microservices architecture requires careful planning and adherence to best practices. While the journey may be complex, following these guidelines will help create robust, scalable, and maintainable systems.\n\n## Further Reading\n\n1. Building Microservices (Sam Newman)\n2. Domain-Driven Design (Eric Evans)\n3. Kubernetes Documentation\n4. Spring Cloud Documentation",
            "url": "https://www.dibakarmitra.com/notes/microservices-best-practices",
            "title": "Microservices Architecture: Best Practices and Design Patterns",
            "summary": "Essential best practices and patterns for building robust microservices architectures",
            "date_modified": "2023-12-10T00:00:00.000Z",
            "author": {
                "name": "Dibakar Mitra",
                "url": "https://www.dibakarmitra.com"
            },
            "tags": [
                "Microservices",
                "System Design",
                "Architecture",
                "DevOps"
            ]
        },
        {
            "id": "https://www.dibakarmitra.com/notes/progressive-web-apps",
            "content_html": "\n# Progressive Web Apps: The Future of Web Development\n\nProgressive Web Apps (PWAs) represent the perfect blend of web and native applications, offering the best of both worlds. Let's explore how to build modern, efficient PWAs and understand their key features.\n\n## What Makes an App a PWA?\n\n### Core Features\n1. **Progressive Enhancement**\n   - Works for every user, regardless of browser\n   - Basic content first, then enhanced features\n\n2. **Responsive Design**\n   - Adapts to any form factor\n   - Mobile-first approach\n\n3. **App-like Experience**\n   - Fast loading\n   - Smooth animations\n   - Native-like interactions\n\n## Essential PWA Components\n\n### 1. Service Workers\nService workers are the backbone of PWAs, enabling:\n- Offline functionality\n- Background sync\n- Push notifications\n\nExample Service Worker Registration:\n```javascript\nif ('serviceWorker' in navigator) {\n  window.addEventListener('load', () => {\n    navigator.serviceWorker.register('/sw.js')\n      .then(registration => {\n        console.log('SW registered:', registration);\n      })\n      .catch(error => {\n        console.log('SW registration failed:', error);\n      });\n  });\n}\n```\n\n### 2. Web App Manifest\nThe manifest.json file defines how your app appears:\n```json\n{\n  \"name\": \"My PWA App\",\n  \"short_name\": \"PWA\",\n  \"start_url\": \"/\",\n  \"display\": \"standalone\",\n  \"background_color\": \"#ffffff\",\n  \"theme_color\": \"#000000\",\n  \"icons\": [\n    {\n      \"src\": \"/icon-192x192.png\",\n      \"sizes\": \"192x192\",\n      \"type\": \"image/png\"\n    }\n  ]\n}\n```\n\n## Performance Optimization\n\n### 1. Caching Strategies\n- Cache-first for static assets\n- Network-first for dynamic content\n- Stale-while-revalidate for balance\n\n### 2. Loading Performance\n- Implement lazy loading\n- Use image optimization\n- Minimize main thread work\n- Implement code splitting\n\n## Advanced PWA Features\n\n### 1. Push Notifications\nEngage users with timely updates:\n- Request permission appropriately\n- Send relevant notifications\n- Handle notification clicks\n\n### 2. Background Sync\nHandle offline actions:\n- Queue failed requests\n- Retry when online\n- Maintain data consistency\n\n### 3. App Shell Architecture\nImplement the app shell model:\n- Instant loading\n- Reliable performance\n- Native-like navigation\n\n## Testing and Debugging\n\n### Tools\n1. **Lighthouse**\n   - Performance metrics\n   - PWA checklist\n   - Best practices\n\n2. **Chrome DevTools**\n   - Service worker debugging\n   - Cache inspection\n   - Network analysis\n\n## Best Practices\n\n### 1. Performance\n- Implement PRPL pattern\n- Use service worker strategies\n- Optimize critical rendering path\n\n### 2. User Experience\n- Provide offline feedback\n- Add to home screen prompt\n- Smooth transitions\n\n### 3. Security\n- Serve over HTTPS\n- Implement proper CSP\n- Handle sensitive data carefully\n\n## Common Challenges\n\n1. **Browser Support**\n   - Implement feature detection\n   - Provide fallbacks\n   - Progressive enhancement\n\n2. **Cache Management**\n   - Version control\n   - Cache invalidation\n   - Storage limits\n\n## Future of PWAs\n\n- Web Assembly integration\n- Advanced APIs\n- Better platform integration\n- Improved app store presence\n\n## Conclusion\n\nPWAs continue to evolve and provide an excellent solution for delivering fast, reliable, and engaging web applications. By following these best practices and implementing key features correctly, you can create PWAs that rival native apps in functionality and user experience.\n\n## Resources\n\n1. Google PWA Documentation\n2. Mozilla Service Workers API\n3. Web App Manifest Specification\n4. Workbox Documentation",
            "url": "https://www.dibakarmitra.com/notes/progressive-web-apps",
            "title": "Progressive Web Apps: The Future of Web Development",
            "summary": "A comprehensive guide to building modern Progressive Web Apps",
            "date_modified": "2023-12-05T00:00:00.000Z",
            "author": {
                "name": "Dibakar Mitra",
                "url": "https://www.dibakarmitra.com"
            },
            "tags": [
                "PWA",
                "Web Development",
                "JavaScript",
                "Performance"
            ]
        },
        {
            "id": "https://www.dibakarmitra.com/notes/nextjs-13-features",
            "content_html": "\n# Next.js 13: A Deep Dive into New Features\n\nNext.js 13 represents a significant leap forward in React-based web development, introducing groundbreaking features that enhance performance, developer experience, and application architecture.\n\n## App Directory (Beta)\n\nThe new app directory introduces a more intuitive way to handle routing and layouts:\n\n```typescript\n// app/layout.tsx\nexport default function RootLayout({\n  children,\n}: {\n  children: React.ReactNode\n}) {\n  return (\n    <html lang=\"en\">\n      <body>{children}</body>\n    </html>\n  )\n}\n```\n\n### Key Benefits\n- Nested layouts\n- Server components by default\n- Simplified routing\n- Improved performance\n\n## Server Components\n\nServer Components represent a paradigm shift in React development:\n\n```typescript\n// app/page.tsx\nasync function getData() {\n  const res = await fetch('https://api.example.com/data')\n  return res.json()\n}\n\nexport default async function Page() {\n  const data = await getData()\n  return <main>{/* Use data */}</main>\n}\n```\n\n### Advantages\n- Reduced client-side JavaScript\n- Improved initial page load\n- Better SEO\n- Simplified data fetching\n\n## Data Fetching\n\n### New Patterns\n1. **Server-side Fetching**\n```typescript\nasync function getData() {\n  const res = await fetch('https://api.example.com/data', {\n    next: { revalidate: 60 } // ISR\n  })\n  return res.json()\n}\n```\n\n2. **Streaming with Suspense**\n```typescript\nimport { Suspense } from 'react'\n\nexport default function Page() {\n  return (\n    <Suspense fallback={<Loading />}>\n      <SlowComponent />\n    </Suspense>\n  )\n}\n```\n\n## Turbopack (Alpha)\n\nNext.js 13 introduces Turbopack, a Rust-based successor to Webpack:\n- Up to 700x faster updates than Webpack\n- Intelligent caching\n- Optimized for Next.js\n\n## Image Component Improvements\n\nThe new Image component is more powerful:\n\n```typescript\nimport Image from 'next/image'\n\nexport default function Gallery() {\n  return (\n    <Image\n      src=\"/photo.jpg\"\n      alt=\"Description\"\n      width={500}\n      height={300}\n      priority\n    />\n  )\n}\n```\n\n### New Features\n- Better performance\n- Improved lazy loading\n- Enhanced accessibility\n- Native image optimization\n\n## Font Optimization\n\nBuilt-in font optimization:\n\n```typescript\nimport { Inter } from 'next/font/google'\n\nconst inter = Inter({ subsets: ['latin'] })\n\nexport default function RootLayout({\n  children,\n}: {\n  children: React.ReactNode\n}) {\n  return (\n    <html lang=\"en\" className={inter.className}>\n      <body>{children}</body>\n    </html>\n  )\n}\n```\n\n## Middleware Enhancements\n\nMore powerful middleware capabilities:\n\n```typescript\n// middleware.ts\nimport { NextResponse } from 'next/server'\nimport type { NextRequest } from 'next/server'\n\nexport function middleware(request: NextRequest) {\n  const requestHeaders = new Headers(request.headers)\n  requestHeaders.set('x-custom-header', 'custom-value')\n\n  return NextResponse.next({\n    request: {\n      headers: requestHeaders,\n    },\n  })\n}\n```\n\n## SEO Improvements\n\nEnhanced metadata API:\n\n```typescript\nimport { Metadata } from 'next'\n\nexport const metadata: Metadata = {\n  title: 'My Page',\n  description: 'Page description',\n  openGraph: {\n    title: 'My Page',\n    description: 'Page description',\n    images: ['/og-image.jpg'],\n  },\n}\n```\n\n## Performance Optimizations\n\n1. **Automatic Code Splitting**\n2. **Improved Static Generation**\n3. **Enhanced Edge Runtime Support**\n\n## Best Practices\n\n### 1. Server Components Usage\n- Use for data fetching\n- Keep client components minimal\n- Leverage streaming\n\n### 2. Route Organization\n- Group related routes\n- Use loading.tsx for suspense\n- Implement error boundaries\n\n### 3. Performance\n- Optimize images\n- Use built-in font optimization\n- Implement proper caching\n\n## Migration Guide\n\n1. **Update Dependencies**\n2. **Move to App Directory**\n3. **Adapt Data Fetching**\n4. **Update Components**\n\n## Conclusion\n\nNext.js 13 brings revolutionary changes to React development, offering improved performance, better developer experience, and more powerful features. While some features are still in beta/alpha, they represent the future of web development.\n\n## Resources\n\n1. Next.js Documentation\n2. React Server Components RFC\n3. Turbopack Documentation\n4. Next.js GitHub Repository",
            "url": "https://www.dibakarmitra.com/notes/nextjs-13-features",
            "title": "Next.js 13: A Deep Dive into New Features",
            "summary": "Exploring the revolutionary features and improvements in Next.js 13",
            "date_modified": "2023-12-01T00:00:00.000Z",
            "author": {
                "name": "Dibakar Mitra",
                "url": "https://www.dibakarmitra.com"
            },
            "tags": [
                "Next.js",
                "React",
                "Web Development",
                "JavaScript"
            ]
        }
    ]
}