<?xml version="1.0" encoding="utf-8"?>
<feed xmlns="http://www.w3.org/2005/Atom">
    <id>https://www.dibakarmitra.com/</id>
    <title>Dibakar Mitra - Software Developer Portfolio</title>
    <updated>2026-06-01T16:15:58.625Z</updated>
    <generator>Feed for Node.js</generator>
    <link rel="alternate" href="https://www.dibakarmitra.com/"/>
    <link rel="self" href="https://www.dibakarmitra.com/api/feed/atom.xml"/>
    <subtitle>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.</subtitle>
    <rights>All rights reserved 2026, Dibakar Mitra - Software Developer Portfolio</rights>
    <entry>
        <title type="html"><![CDATA[ Activity Scope: Laravel Audit Trail Package]]></title>
        <id>https://www.dibakarmitra.com/notes/activity-scope</id>
        <link href="https://www.dibakarmitra.com/notes/activity-scope"/>
        <updated>2025-12-20T00:00:00.000Z</updated>
        <content type="html"><![CDATA[
# Activity Scope: Laravel Audit Trail Package

Looking 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.

## Why Activity Scope?

In modern Laravel development, tracking user actions and maintaining audit trails is essential. Most existing solutions either:

- Are overly complex with steep learning curves
- Sacrifice performance for features  
- Ignore privacy concerns in modern applications
- Force rigid logging patterns

Activity Scope changes this with a thoughtful approach that prioritizes what developers actually need.

## Key Features

### Fluent Builder API

```php
activity()
    ->on($post)
    ->did('published')
    ->with(['scheduled_at' => now()])
    ->success()
    ->log();
```

Clean, readable, and chainable API that makes sense.

### Smart Actor Resolution

```php
// Automatically uses auth()->user()
activity()->created($post)->log();

// Override when needed
activity()->by($admin)->on($user)->did('suspended')->log();
```

Works the way you expect, with sensible defaults.

### Privacy-First Design

```php
activity()
    ->sensitive()
    ->with(['api_key' => 'sk_live_123456']) // Auto-redacted
    ->log();
```

Built-in IP anonymization, sensitive data scrubbing, and privacy controls.

### Modular Traits

```php
// Automatic logging
class Post extends Model {
    use LogsActivity;
}

// Manual control
class User extends Model {
    use HasActivities;
    
    function login() {
        $this->newActivity()->did('logged_in')->log();
    }
}
```

Use what you need, ignore what you don't.

## Getting Started

### Installation

```bash
composer require dibakar/activity-scope
php artisan activityscope:install
php artisan migrate
```

### Your First Activity Log

```php
// That's it. You're ready.
activity()
    ->on($user)
    ->did('registered')
    ->log();
```

## Real-World Use Cases

### E-commerce Order Tracking

```php
class OrderService {
    public function processOrder(Order $order, User $user) {
        activity()
            ->by($user)
            ->created($order)
            ->with(['total' => $order->total, 'items' => $order->items->count()])
            ->tags(['order', 'ecommerce'])
            ->log();
            
        if ($payment->successful) {
            activity()
                ->by($user)
                ->on($order)
                ->did('payment_confirmed')
                ->success()
                ->log();
        }
    }
}
```

### Security Event Logging

```php
// Failed login attempts
activity()
    ->byGuest()
    ->on($user)
    ->failed('Invalid credentials')
    ->severity('warning')
    ->tags(['auth', 'security'])
    ->log();

// Admin actions
activity()
    ->by($admin)
    ->on($user)
    ->did('account_suspended')
    ->severity('critical')
    ->tags(['admin', 'security'])
    ->log();
```

### Analytics Integration

```php
// Track user engagement
activity()
    ->by($user)
    ->on($article)
    ->did('viewed')
    ->with(['duration' => $readingTime, 'source' => 'search'])
    ->tags(['analytics', 'engagement'])
    ->log();
```

## Advanced Features

### Human-Readable Messages

```php
$activity = Activity::first();
echo $activity->message(); 
// "John Doe published Post 'Getting Started with Laravel' 2 minutes ago"
```

### Powerful Query Scopes

```php
// Find all admin actions in last week
$adminActions = Activity::by($admin)
    ->where('created_at', '>=', now()->subDays(7))
    ->where('severity', 'critical')
    ->get();

// Security events
$securityEvents = Activity::withTag('security')
    ->failed()
    ->get();
```

### Performance Optimized

- Efficient Queries: Optimized database interactions
- Queue Support: Async logging when you need it
- Smart Pruning: Automatic cleanup of old logs
- Minimal Overhead: Won't slow down your application

## Security & Compliance

### GDPR Compliant

```php
// Automatic privacy controls
'privacy' => [
    'sanitize_data' => true,
    'anonymize_ip' => true,
    'sensitive_fields' => [
        'password', 'token', 'api_key', 'credit_card', 'ssn'
    ],
],
```

### Audit Trail Standards

- Immutable logs (once written, never changed)
- Complete context (who, what, when, where)
- Tamper-evident (cryptographic hashes available)
- Searchable and filterable

## Developer Experience

### Clean Configuration

```php
// Simple, sensible defaults
return [
    'enabled' => env('ACTIVITY_LOGGER_ENABLED', true),
    'auto_log' => env('ACTIVITY_LOGGER_AUTO_LOG', false),
    'privacy' => [
        'sanitize_data' => true,
        'track_ip_address' => true,
        'anonymize_ip' => false,
    ],
];
```

### Comprehensive Testing

```php
// Built-in test helpers
$this->assertActivityLogged('created', $post);
$this->assertDatabaseHas('activities', [
    'action' => 'published',
    'subject_id' => $post->id
]);
```

## Why Choose Activity Scope?

1. **Purpose-Built**: Designed specifically for Laravel's ecosystem
2. **Privacy-First**: Security and compliance built-in
3. **Performance**: Won't slow down your application
4. **Flexible**: Use what you need, ignore what you don't
5. **Intuitive**: API that just makes sense
6. **Production-Ready**: Battle-tested in real applications

## Resources

- **Documentation**: [Complete API Reference](https://github.com/dibakarmitra/activity-scope/blob/main/API.md)
- **GitHub**: [Repository & Issues](https://github.com/dibakarmitra/activity-scope)
- **Packagist**: [Install via Composer](https://packagist.org/packages/dibakar/activity-scope)
- **Examples**: [Real-world code samples](https://github.com/dibakarmitra/activity-scope/tree/main/examples)

## Get Started Today

Stop fighting with complex logging solutions. Activity Scope gives you the power, flexibility, and privacy features you need.

```bash
composer require dibakar/activity-scope
```

Your future self will thank you for choosing a logging solution that actually respects your time and your users' privacy.

---

**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.

---

#Laravel #PHP #AuditTrail #ActivityLogging #OpenSource #DeveloperTools
]]></content>
        <author>
            <name>Dibakar Mitra</name>
            <email>dibakarmitra07@gmail.com</email>
            <uri>https://www.dibakarmitra.com</uri>
        </author>
        <category label="Laravel" term="Laravel"/>
        <category label="PHP" term="PHP"/>
        <category label="Audit Trails" term="Audit Trails"/>
        <category label="Activity Logging" term="Activity Logging"/>
        <category label="Laravel Package" term="Laravel Package"/>
    </entry>
    <entry>
        <title type="html"><![CDATA[Config-Ship: Lightweight Configuration Resolver for Node.js]]></title>
        <id>https://www.dibakarmitra.com/notes/config-ship-package</id>
        <link href="https://www.dibakarmitra.com/notes/config-ship-package"/>
        <updated>2025-12-18T00:00:00.000Z</updated>
        <summary type="html"><![CDATA[A lightweight, package-safe configuration resolver with layered defaults, env, and runtime overrides.]]></summary>
        <content type="html"><![CDATA[
# Config-Ship: Simple and Safe Configuration Management

Config-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.

## Key Features

- **Layered Configuration**: Combine defaults, environment variables, and runtime overrides
- **Package-Safe**: Designed to work well in both ESM and CommonJS modules
- **Minimal Dependencies**: Lightweight with minimal external dependencies
- **TypeScript Support**: Built with TypeScript for better developer experience
- **Runtime Access**: Get and set configuration values at runtime

## Installation

Install Config-Ship using your preferred package manager:

```bash
# Using npm
npm install config-ship

# Using yarn
yarn add config-ship

# Using pnpm
pnpm add config-ship
```

## Basic Usage

### 1. Create a Configuration File

Create a configuration file (e.g., `app.config.ts`):

```typescript
// app.config.ts
export default {
  app: {
    name: "MyApp",
    version: "1.0.0"
  },
  server: {
    host: "localhost",
    port: 3000,
    environment: process.env.NODE_ENV || "development"
  },
  features: {
    darkMode: true,
    notifications: true
  }
};
```

### 2. Use the Configuration in Your Application

```typescript
// app.ts
import { createConfig } from 'config-ship';
import config from './app.config.js';

// Initialize the configuration
const appConfig = createConfig({
  defaults: config,
  envPrefix: 'APP_',  // Optional: prefix for environment variables
  envFile: '.env'     // Optional: path to .env file
});

// Access configuration values
console.log(`Starting ${appConfig.get('app.name')} v${appConfig.get('app.version')}`);
console.log(`Server running at http://${appConfig.get('server.host')}:${appConfig.get('server.port')}`);

// Check feature flags
if (appConfig.get('features.darkMode')) {
  console.log('Dark mode is enabled');
}
```

## Environment Variables

Config-Ship can load environment variables from a `.env` file or `process.env`. By default, it looks for a `.env` file in your project root.

Example `.env` file:
```env
APP_SERVER_PORT=4000
APP_FEATURES_DARKMODE=false
```

Environment 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_`.

## Runtime Configuration

You can modify configuration values at runtime:

```typescript
// Set a configuration value at runtime
appConfig.set('server.port', 4000);

// Check if a configuration key exists
if (appConfig.has('features.notifications')) {
  console.log('Notifications feature exists');
}

// Get all configuration
const allConfig = appConfig.all();
console.log('Full configuration:', allConfig);
```

## TypeScript Support

Config-Ship is written in TypeScript and provides excellent type support:

```typescript
// types.ts
interface AppConfig {
  app: {
    name: string;
    version: string;
  };
  server: {
    host: string;
    port: number;
    environment: 'development' | 'production' | 'test';
  };
  features: {
    darkMode: boolean;
    notifications: boolean;
  };
}

// app.ts
import { createConfig } from 'config-ship';
import config from './app.config.js';

const appConfig = createConfig<AppConfig>({
  defaults: config
});

// Type-safe access
const port: number = appConfig.get('server.port');
```

## Best Practices

1. **Keep Sensitive Data Secure**: Use environment variables for secrets and sensitive information.
2. **Use TypeScript**: Take advantage of TypeScript for better type safety and autocompletion.
3. **Document Configuration**: Document available configuration options and their purposes.
4. **Environment-Specific Configs**: Use environment variables to adjust configuration between different environments.
5. **Validate Early**: Validate configuration on application startup to catch issues early.

## API Reference

### `createConfig(options)`: ConfigInstance

Creates a new configuration instance.

**Options:**
- `defaults`: Object containing default configuration values
- `envPrefix`: Prefix for environment variables (default: '')
- `envFile`: Path to .env file (default: '.env')
- `rootFile`: Path to root directory for resolving relative paths (default: process.cwd())

**Returns:**
- `get(key: string): any` - Get a configuration value by dot notation
- `set(key: string, value: any): void` - Set a configuration value
- `has(key: string): boolean` - Check if a configuration key exists
- `all(): object` - Get all configuration values

## Best Practices

1. **Keep Sensitive Data Secure**: Never commit sensitive information directly in your configuration files. Use environment variables for secrets.
2. **Use Environment-Specific Configs**: Take advantage of environment-specific overrides to manage different deployment environments.
3. **Validate Early**: Add validation to catch configuration errors as early as possible.
4. **Document Your Configuration**: Maintain clear documentation for all configuration options and their purposes.

## Conclusion

Config-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.

For more advanced usage and API documentation, check out the [official GitHub repository](https://github.com/dibakarmitra/config-ship).

## License

This project is open-source and available under the MIT License.
]]></content>
        <author>
            <name>Dibakar Mitra</name>
            <email>dibakarmitra07@gmail.com</email>
            <uri>https://www.dibakarmitra.com</uri>
        </author>
        <category label="javaScript" term="javaScript"/>
        <category label="configuration" term="configuration"/>
        <category label="node.js" term="node.js"/>
        <category label="typescript" term="typescript"/>
        <category label="esm" term="esm"/>
        <category label="config" term="config"/>
    </entry>
    <entry>
        <title type="html"><![CDATA[Laravel Dynamic Filters: A Comprehensive Guide to Flexible Query Building]]></title>
        <id>https://www.dibakarmitra.com/notes/laravel-dynamic-filters</id>
        <link href="https://www.dibakarmitra.com/notes/laravel-dynamic-filters"/>
        <updated>2025-09-18T00:00:00.000Z</updated>
        <summary type="html"><![CDATA[Learn how to implement powerful, flexible filtering in your Laravel applications with the Laravel Dynamic Filters package.]]></summary>
        <content type="html"><![CDATA[
# Laravel Dynamic Filters

A 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.

## ✨ Key Features

- **Expressive Filtering**: Chainable methods and intuitive syntax for complex queries
- **Advanced Search**: Full-text search with fuzzy matching and term normalization
- **Relationship Support**: Filter across model relationships with nested conditions
- **Type Safety**: Strict type checking and automatic value casting
- **Performance Optimized**: Efficient query building with minimal overhead
- **Security First**: Whitelisting and input validation out of the box
- **Extensible**: Easy to create and register custom filters
- **Modern PHP**: Built with PHP 8.1+ features and type hints

## 🚀 Installation

### Requirements
- PHP 8.1 or higher
- Laravel 10.x or later
- Composer

### Install via Composer
```bash
composer require dibakar/laravel-dynamic-filters
```

### Publish Configuration (Optional)
```bash
php artisan vendor:publish --provider="Dibakar\LaravelDynamicFilters\DynamicFiltersServiceProvider" --tag="config"
```

## 🚀 Quick Start

### 1. Prepare Your Model

Add the `HasDynamicFilter` trait to your Eloquent model and define the filterable, searchable, and sortable fields:

```php
use Dibakar\LaravelDynamicFilters\Traits\HasDynamicFilter;
use Illuminate\Database\Eloquent\Model;

class Post extends Model
{
    use HasDynamicFilter;

    /**
     * Fields that can be searched.
     */
    protected $searchable = [
        'title',
        'content',
        'author.name',       // Search in relationships
        'tags.name'          // Search in many-to-many relationships
    ];

    /**
     * Fields that can be filtered with operators.
     */
    protected $filterable = [
        'id',
        'status',
        'category_id',
        'published_at',
        'views',
        'is_featured',
    ];

    /**
     * Fields that can be used for sorting.
     */
    protected $sortable = [
        'created_at' => 'desc',  // Default sort
        'title' => 'asc',
        'views' => 'desc',
    ];
}
```

### 2. Basic Filtering

Filter your models using query parameters in your controller:

```php
// GET /posts?status=published&created_at[gt]=2023-01-01&sort=-views,title
public function index(Request $request)
{
    $posts = Post::filter($request->query())
        ->with(['author', 'category', 'tags']) // Eager load relationships
        ->paginate($request->per_page ?? 15);

    return response()->json($posts);
}
```

### 3. Search Functionality

Search across searchable fields with a simple API:

```php
// GET /posts?q=laravel+framework
public function search(Request $request)
{
    $posts = Post::search($request->q)
        ->filter($request->except('q')) // Apply additional filters
        ->paginate($request->per_page ?? 15);

    return response()->json($posts);
}
```

### 4. Sorting Results

Sort your results using the `sort` parameter in your requests. The `-` prefix indicates descending order.

```php
// In your controller
$posts = Post::sort($request->input('sort'))->get();

// Or chain it with filters
$posts = Post::filter($filters)
    ->sort($request->input('sort', 'created_at,desc'))
    ->paginate(15);
```

Example requests:
```
GET /posts?sort=title             // Sort by title (ascending)
GET /posts?sort=title,asc         // Same as above (explicit ascending)
GET /posts?sort=title,desc        // Sort by title (descending)
GET /posts?sort=-title            // Alternative: Sort by title (descending)
GET /posts?sort=views,desc&sort=title,asc  // Multiple sort fields
```

### 5. Pagination

Pagination works seamlessly with Laravel's built-in pagination:

```php
// GET /posts?page=2&per_page=20
$posts = Post::filter($request->query())
    ->paginate($request->per_page ?? 15);
```

## 🚀 Advanced Usage

### Complex Filter Groups

Create complex filter conditions with AND/OR logic:

```php
// Example: (status = 'published' AND (title LIKE '%Laravel%' OR views > 100)) AND (author_id = 1 OR author_id = 2)
$filters = [
    '_group' => [
        'boolean' => 'and',
        'filters' => [
            'status' => 'published',
        ],
        'nested' => [
            [
                'boolean' => 'or',
                'filters' => [
                    'title' => ['like' => '%Laravel%'],
                    'views' => ['gt' => 100],
                ],
            ],
            [
                'boolean' => 'or',
                'filters' => [
                    'author_id' => [1, 2],
                ],
            ],
        ],
    ],
];

$posts = Post::filter($filters)->get();
```

### Custom Filter Classes

For complex filtering logic, create a custom filter class:

```php
<?php

namespace App\Filters;

use Dibakar\LaravelDynamicFilters\Contracts\FilterContract;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Support\Carbon;

class PublishedInLastDaysFilter implements FilterContract
{
    public function apply(Builder $query, $value, string $property): Builder
    {
        $days = is_numeric($value) ? (int) $value : 7; // Default to 7 days if invalid
        return $query->where('published_at', '>=', Carbon::now()->subDays($days));
    }

    public function validate($value): bool
    {
        return is_numeric($value) && $value > 0;
    }

    public function getValidationMessage(): string
    {
        return 'The days parameter must be a positive number.';
    }
}
```

Register your custom filter in `config/dynamic-filters.php`:

```php
'custom_filters' => [
    'published_in_days' => \App\Filters\PublishedInLastDaysFilter::class,
    // Add more custom filters as needed
],
```

Now use it in your API:

```
// GET /posts?published_in_days=30
$recentPosts = Post::filter(request()->query())->get();
```

## Available Operators

| Operator | Description | Example |
|----------|-------------|---------|
| `=` | Equals | `?status=active` |
| `neq` | Not equals | `?status[neq]=inactive` |
| `gt` | Greater than | `?views[gt]=100` |
| `gte` | Greater than or equal | `?rating[gte]=4` |
| `lt` | Less than | `?price[lt]=100` |
| `lte` | Less than or equal | `?age[lte]=30` |
| `like` | Case-sensitive pattern matching | `?name[like]=%john%` |
| `ilike` | Case-insensitive pattern matching | `?email[ilike]=%gmail.com` |
| `in` | Value is in list | `?status[in]=active,pending` |
| `not_in` | Value is not in list | `?id[not_in]=1,2,3` |
| `between` | Value is between two values | `?created_at[between]=2023-01-01,2023-12-31` |
| `null` | Field is null | `?deleted_at[null]` |
| `notnull` | Field is not null | `?updated_at[notnull]` |

## Performance Optimization

### Database Indexing

```php
// In a migration
public function up()
{
    Schema::table('posts', function (Blueprint $table) {
        // Single column indexes
        $table->index('status');
        $table->index('published_at');
        $table->index('views');
        
        // Composite index for common filter combinations
        $table->index(['status', 'published_at']);
        $table->index(['category_id', 'status', 'published_at']);
    });
}
```

### Selective Field Loading

```php
// Only select the fields you need
$posts = Post::select([
        'id', 'title', 'slug', 'excerpt',
        'status', 'published_at', 'author_id', 'category_id'
    ])
    ->with([
        'author:id,name,avatar',
        'category:id,name,slug',
        'tags:id,name,slug'
    ])
    ->filter($filters)
    ->paginate(15);
```

## Security

By default, only fields defined in the `$filterable` array can be filtered. This is a security measure to prevent unauthorized filtering on sensitive fields.

You can also define a global whitelist in the config file that applies to all models:

```php
'global_whitelist' => [
    'id',
    'status',
    'created_at',
    'updated_at',
],
```

## Conclusion

Laravel 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.

## Resources

- [GitHub Repository](https://github.com/dibakarmitra/laravel-dynamic-filters)
- [Packagist](https://packagist.org/packages/dibakar/laravel-dynamic-filters)
- [Issues](https://github.com/dibakarmitra/laravel-dynamic-filters/issues)

## License

The MIT License (MIT). Please see [License File](https://github.com/dibakarmitra/laravel-dynamic-filters/blob/main/LICENSE.md) for more information.
]]></content>
        <author>
            <name>Dibakar Mitra</name>
            <email>dibakarmitra07@gmail.com</email>
            <uri>https://www.dibakarmitra.com</uri>
        </author>
        <category label="laravel" term="laravel"/>
        <category label="php" term="php"/>
        <category label="query-builder" term="query-builder"/>
        <category label="api" term="api"/>
        <category label="filters" term="filters"/>
    </entry>
    <entry>
        <title type="html"><![CDATA[Laravel Ownership Package – Simplify Model Ownership in Laravel]]></title>
        <id>https://www.dibakarmitra.com/notes/laravel-ownership</id>
        <link href="https://www.dibakarmitra.com/notes/laravel-ownership"/>
        <updated>2025-09-05T00:00:00.000Z</updated>
        <content type="html"><![CDATA[
# Laravel Ownership Package – Simplify Model Ownership in Laravel

Managing 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.

## 🚀 What is Laravel Ownership?
This 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.

## ✨ Features
- Polymorphic ownership handling out of the box.  
- Easy to integrate with existing models.  
- Supports roles for more advanced ownership structures.  
- Database migration included (`ownerships` table).  
- Works seamlessly with **Laravel 9, 10, and 11**.  

## 📦 Installation

1. Require the package:
   ```bash
   composer require dibakar/laravel-ownership
   ```

   *(if you’re testing the dev branch, use `composer require dibakar/laravel-ownership:dev-main`)*

2. Publish and run the migration:
   ```bash
   php artisan vendor:publish --tag=ownership-migrations
   php artisan migrate
   ```

3. Add the `HasOwnership` trait to your models:
   ```php
   use Dibakar\Ownership\Traits\HasOwnership;

   class Project extends Model
   {
       use HasOwnership;
   }
   ```

## 🔧 Usage Example
```php
$project = Project::find(1);
$user = User::find(1);

// Assign ownership
$project->addOwner($user, 'manager');

// Check ownership
if ($project->isOwnedBy($user)) {
    echo "User owns this project!";
}
```

## 🤝 Why Use This Package?
- Keeps your code clean and DRY.  
- Avoids writing repetitive relationship logic.  
- Flexible enough to handle **teams, clients, vendors, or multi-role ownership**.  

## 📚 Resources
- [GitHub Repository](https://github.com/dibakarmitra/laravel-ownership)  
- [Packagist Package](https://packagist.org/packages/dibakar/laravel-ownership)  

## License
This package is open-source and available under the MIT License.

Make ownership handling in Laravel easy and maintainable with **dibakar/laravel-ownership**. 🚀
]]></content>
        <author>
            <name>Dibakar Mitra</name>
            <email>dibakarmitra07@gmail.com</email>
            <uri>https://www.dibakarmitra.com</uri>
        </author>
        <category label="Laravel" term="Laravel"/>
        <category label="PHP" term="PHP"/>
        <category label="Package" term="Package"/>
        <category label="Ownership" term="Ownership"/>
        <category label="Eloquent" term="Eloquent"/>
    </entry>
    <entry>
        <title type="html"><![CDATA[Building a Clean and Consistent Laravel API Response System]]></title>
        <id>https://www.dibakarmitra.com/notes/laravel-api-response-system</id>
        <link href="https://www.dibakarmitra.com/notes/laravel-api-response-system"/>
        <updated>2025-05-02T00:00:00.000Z</updated>
        <content type="html"><![CDATA[
# How to Build a Clean and Consistent Laravel API Response System

When 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.

## Step 1: Create a Base Controller for API Responses

Let’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.

### Key Features:

- Unified format for JSON responses
- Optional data encryption
- Standard HTTP status messages
- Pagination support

```php
class Controller extends BaseController
{
    use AuthorizesRequests, DispatchesJobs, ValidatesRequests;

    protected $errorMessages = [ /* HTTP status messages */ ];

    protected function isEncryptionEnabled(): bool
    {
        return false; // Toggle encryption here
    }

    protected function getRequestData($request): array
    {
        if ($this->isEncryptionEnabled()) {
            $decrypted = app('securityService')->decrypt($request->input, $request->version ?? false);
            return json_decode($decrypted, true) ?? [];
        }

        return $request->all();
    }

    protected function sendSuccess($data = null, $message = null, int $status = 200): JsonResponse
    {
        return $this->sendResponse('success', $status, $message, $data);
    }

    protected function sendError($message = null, int $status = 400): JsonResponse
    {
        if (!isset($this->errorMessages[$status])) $status = 400;
        return $this->sendResponse('error', $status, $message);
    }

    protected function validationError($message, $response = null): JsonResponse
    {
        return $this->sendResponse('error', 422, $message, $response);
    }

    protected function sendResponse(string $status, int $statusCode, $message = null, $data = null): JsonResponse
    {
        $statusMessage = $this->errorMessages[$statusCode] ?? 'Unknown Status';
        $framed = $this->frameResponse($status, $statusCode, $statusMessage, $message, $this->prepareResponseData($data));
        return response()->json($framed, $statusCode);
    }

    protected function frameResponse(string $status, int $statusCode, string $statusMessage, $message = null, $data = null): array
    {
        if ($data instanceof LengthAwarePaginator) {
            $data = $this->formatPaginatedResponse($data);
        }

        return compact('status', 'statusCode', 'statusMessage', 'message', 'data');
    }

    protected function prepareResponseData($data)
    {
        return $this->isEncryptionEnabled() ? app('securityService')->encrypt(json_encode($data)) : $data;
    }

    protected function formatPaginatedResponse($paginator, bool $showLinks = false): array
    {
        $items = $paginator->items();

        $response = [
            'current_page' => (int)$paginator->currentPage(),
            'items' => $items,
            'last_page' => (int)$paginator->lastPage(),
            'per_page' => (int)$paginator->perPage(),
            'from' => (int)$paginator->firstItem(),
            'to' => (int)$paginator->lastItem(),
            'total' => (int)$paginator->total(),
        ];

        if ($showLinks) {
            $response['next_page_url'] = $paginator->nextPageUrl();
            $response['prev_page_url'] = $paginator->previousPageUrl();
        }

        return $response;
    }
}
```

## Step 2: Add a Bulk Delete API Endpoint

With the base response methods in place, implementing consistent endpoints becomes easy.

Here’s an example `bulkDelete` method that validates input, checks authorization, and uses the unified response system.

```php
public function bulkDelete(Request $request)
{
    $validator = Validator::make($request->all(), [
        'ids' => 'required|array',
        'ids.*' => 'exists:invoices,id',
    ]);

    if ($validator->fails()) {
        return $this->validationError($validator->errors());
    }

    try {
        $unauthorized = Invoice::whereIn('id', $request->ids)
            ->where('user_id', '!=', backpack_user()->id)
            ->exists();

        if ($unauthorized) {
            return $this->sendError('Unauthorized action.', 403);
        }

        $deletedCount = $this->invoiceService->bulkDelete($request->ids);

        return $this->sendSuccess([], "{$deletedCount} invoices deleted.");
    } catch (Exception $e) {
        recordError('Failed to delete invoices', $e);
        return $this->sendError('Failed to delete invoices.', 500);
    }
}
```

## Benefits of This Approach

- **Clarity:** Your API always responds in the same JSON format.
- **Maintainability:** Changes to the response structure happen in one place.
- **Security:** Easily toggle request/response encryption if needed.
- **Professionalism:** Clients and frontend developers will appreciate the consistency.

## Conclusion

A 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.

Need help expanding this with authentication, filtering, or pagination features? Just ask.
]]></content>
        <author>
            <name>Dibakar Mitra</name>
            <email>dibakarmitra07@gmail.com</email>
            <uri>https://www.dibakarmitra.com</uri>
        </author>
        <category label="Laravel" term="Laravel"/>
        <category label="PHP" term="PHP"/>
        <category label="API Development" term="API Development"/>
        <category label="Backend" term="Backend"/>
        <category label="Web Security" term="Web Security"/>
    </entry>
    <entry>
        <title type="html"><![CDATA[Laravel 12 – What's New & How to Get Started]]></title>
        <id>https://www.dibakarmitra.com/notes/laravel12</id>
        <link href="https://www.dibakarmitra.com/notes/laravel12"/>
        <updated>2025-03-11T00:00:00.000Z</updated>
        <content type="html"><![CDATA[
# Laravel 12 – What's New & How to Get Started

Laravel 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.

## What's New in Laravel 12?

### 🚀 Modern Starter Kits
Laravel 12 brings new starter kits for React, Vue, and Livewire. These kits come with:
- **Inertia.js** for seamless single-page app experiences.
- **TypeScript** for better maintainability.
- **Tailwind CSS & ShadCN UI** for a sleek design.
- **WorkOS AuthKit** (optional) for easy social login, passkeys, and SSO.

### 🔥 Faster & More Efficient
- **xxHash replaces MD5**, making hashing faster.
- **UUID v7 support**, improving database indexing.
- **MariaDB CLI Support**, so you can now use MariaDB natively in Laravel.
- **Collection::range now includes a step parameter**, making sequence generation more flexible.

### 🔧 Easier Debugging
- **`debug()->suggest()`** helps identify issues faster by suggesting solutions in real-time.

### 🔑 Stronger Password Security
- **New password validation rules** to enforce stronger passwords.

## How to Install Laravel 12

Getting started with Laravel 12 is easy. Just follow these steps:

1. **Install Laravel globally (if you haven't already):**
   ```bash
   composer global require laravel/installer
   ```

2. **Create a new Laravel 12 project:**
   ```bash
   laravel new myproject
   cd myproject
   ```

3. **Install dependencies:**
   ```bash
   composer install
   ```

4. **Set up your environment file:**
   ```bash
   cp .env.example .env
   ```
   Configure your database and other settings in `.env`.

5. **Generate an application key:**
   ```bash
   php artisan key:generate
   ```

6. **Run database migrations:**
   ```bash
   php artisan migrate
   ```

7. **Start the development server:**
   ```bash
   php artisan serve
   ```
   Your Laravel 12 app is now running at `http://localhost:8000`! 🎉

## Why Upgrade to Laravel 12?
- **Minimal breaking changes** – upgrading is easy.
- **Better performance** with faster hashing and indexing.
- **More tools for modern web apps** like React, Vue, and Livewire.
- **Improved security** with stronger password validation.

## License
This project is open-source and available under the MIT License.

Laravel 12 makes development smoother and more powerful. Ready to build something amazing? 🚀

]]></content>
        <author>
            <name>Dibakar Mitra</name>
            <email>dibakarmitra07@gmail.com</email>
            <uri>https://www.dibakarmitra.com</uri>
        </author>
        <category label="Laravel" term="Laravel"/>
        <category label="PHP" term="PHP"/>
        <category label="Web Development" term="Web Development"/>
        <category label="Laravel 12" term="Laravel 12"/>
    </entry>
    <entry>
        <title type="html"><![CDATA[Web Security Best Practices for Modern Applications]]></title>
        <id>https://www.dibakarmitra.com/notes/web-security-best-practices</id>
        <link href="https://www.dibakarmitra.com/notes/web-security-best-practices"/>
        <updated>2024-10-25T00:00:00.000Z</updated>
        <content type="html"><![CDATA[
# Web Security Best Practices for Modern Applications

Security is paramount in modern web applications. Let's explore essential practices to protect your applications.

## Authentication

### Secure Password Hashing

```typescript
import * as bcrypt from 'bcrypt';

async function hashPassword(password: string): Promise<string> {
  const saltRounds = 12;
  return await bcrypt.hash(password, saltRounds);
}

async function verifyPassword(password: string, hash: string): Promise<boolean> {
  return await bcrypt.compare(password, hash);
}
```

## JWT Implementation

```typescript
import * as jwt from 'jsonwebtoken';

const JWT_SECRET = process.env.JWT_SECRET!;

interface TokenPayload {
  userId: string;
  role: string;
}

function generateToken(payload: TokenPayload): string {
  return jwt.sign(payload, JWT_SECRET, {
    expiresIn: '1h',
    algorithm: 'HS256'
  });
}

function verifyToken(token: string): TokenPayload {
  try {
    return jwt.verify(token, JWT_SECRET) as TokenPayload;
  } catch (error) {
    throw new Error('Invalid token');
  }
}
```

## XSS Prevention

### Content Security Policy

```typescript
// Express middleware
app.use((req, res, next) => {
  res.setHeader(
    'Content-Security-Policy',
    "default-src 'self'; " +
    "script-src 'self' 'unsafe-inline' 'unsafe-eval'; " +
    "style-src 'self' 'unsafe-inline';"
  );
  next();
});
```

### Input Sanitization

```typescript
import { sanitize } from 'dompurify';

function sanitizeUserInput(input: string): string {
  return sanitize(input, {
    ALLOWED_TAGS: ['b', 'i', 'em', 'strong', 'a'],
    ALLOWED_ATTR: ['href']
  });
}

// Usage in React
function CommentDisplay({ comment }: { comment: string }) {
  return <div dangerouslySetInnerHTML={{ 
    __html: sanitizeUserInput(comment) 
  }} />;
}
```

## CSRF Protection

```typescript
import csurf from 'csurf';

// Express middleware
app.use(csurf());

// React component
function Form() {
  const csrfToken = document.querySelector('meta[name="csrf-token"]')
    ?.getAttribute('content');

  return (
    <form method="POST" action="/api/submit">
      <input type="hidden" name="_csrf" value={csrfToken} />
      {/* form fields */}
    </form>
  );
}
```

## SQL Injection Prevention

```typescript
import { Pool } from 'pg';

const pool = new Pool();

async function getUserById(id: string) {
  // Use parameterized queries
  const query = {
    text: 'SELECT * FROM users WHERE id = $1',
    values: [id],
  };
  
  try {
    const result = await pool.query(query);
    return result.rows[0];
  } catch (error) {
    console.error('Database error:', error);
    throw error;
  }
}
```

## Rate Limiting

```typescript
import rateLimit from 'express-rate-limit';

const limiter = rateLimit({
  windowMs: 15 * 60 * 1000, // 15 minutes
  max: 100, // limit each IP to 100 requests per windowMs
  message: 'Too many requests from this IP, please try again later'
});

// Apply to all routes
app.use(limiter);

// Apply to specific routes
app.use('/api/login', rateLimit({
  windowMs: 60 * 60 * 1000, // 1 hour
  max: 5, // 5 attempts per hour
  message: 'Too many login attempts, please try again later'
}));
```

## Secure Headers

```typescript
import helmet from 'helmet';

app.use(helmet({
  contentSecurityPolicy: {
    directives: {
      defaultSrc: ["'self'"],
      scriptSrc: ["'self'", "'unsafe-inline'"],
      styleSrc: ["'self'", "'unsafe-inline'"],
      imgSrc: ["'self'", "data:", "https:"],
    },
  },
  referrerPolicy: { policy: 'same-origin' }
}));
```

## Best Practices

1. Security Headers
   - Use HTTPS
   - Set secure cookies
   - Implement HSTS
   - Enable CORS properly

2. Authentication
   - Implement MFA
   - Use secure session management
   - Implement proper password policies
   - Handle logout properly

3. Data Protection
   - Encrypt sensitive data
   - Implement proper access control
   - Regular security audits
   - Keep dependencies updated

## Security Checklist

```typescript
interface SecurityChecklist {
  authentication: {
    passwordHashing: boolean;
    mfa: boolean;
    sessionManagement: boolean;
  };
  headers: {
    https: boolean;
    csp: boolean;
    hsts: boolean;
  };
  dataProtection: {
    encryption: boolean;
    accessControl: boolean;
    backups: boolean;
  };
}

const securityAudit: SecurityChecklist = {
  authentication: {
    passwordHashing: true,
    mfa: true,
    sessionManagement: true
  },
  headers: {
    https: true,
    csp: true,
    hsts: true
  },
  dataProtection: {
    encryption: true,
    accessControl: true,
    backups: true
  }
};
```

## Conclusion

Security should be a continuous process, not a one-time implementation. Regular audits and updates are essential to maintain a secure application.
]]></content>
        <author>
            <name>Dibakar Mitra</name>
            <email>dibakarmitra07@gmail.com</email>
            <uri>https://www.dibakarmitra.com</uri>
        </author>
        <category label="Security" term="Security"/>
        <category label="Web Development" term="Web Development"/>
        <category label="Authentication" term="Authentication"/>
        <category label="OWASP" term="OWASP"/>
    </entry>
    <entry>
        <title type="html"><![CDATA[Getting Started with Nextfolio]]></title>
        <id>https://www.dibakarmitra.com/notes/getting-started</id>
        <link href="https://www.dibakarmitra.com/notes/getting-started"/>
        <updated>2024-08-13T00:00:00.000Z</updated>
        <summary type="html"><![CDATA[Instructions to build and configure your Nextfolio portfolio.]]></summary>
        <content type="html"><![CDATA[
Nextfolio includes all the essentials for a stunning portfolio website.

Start 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.

[![Deploy with Vercel](https://vercel.com/button)](https://vercel.com/new/clone?repository-url=https%3A%2F%2Fgithub.com%2F1msirius%2FNextfolio)

## Installation

Nextfolio uses [pnpm](https://pnpm.io/installation) for dependency management, so ensure it is installed on your system.

Execute [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:

```
pnpm create next-app --example https://github.com/1msirius/Nextfolio my-portfolio
```

Start the development server:

```
pnpm dev
```

The server will be running at [http://localhost:3000](http://localhost:3000).

## Configuration

Customize your Nextfolio setup by updating your information to ensure proper SEO, feed generation, Open Graph integration, and other settings.

### Config.ts

Update 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.

```
export const metaData = {
  baseUrl: "https://nextfolio-template.vercel.app", // Update with your site base URL
  title: "Nextfolio", // Update with your site title
  name: "Sirius", // Update with your name
  ogImage: "/opengraph-image.png", // Update with your Open Graph image
  description:
    "A clean, fast, and lightweight portfolio template built with Next.js, Vercel, and Tailwind CSS for optimal performance.", // Update with your site description
};

export const socialLinks = {
  twitter: "https://x.com/1tssirius", // Update with your Twitter URL
  github: "https://github.com/1msirius/Nextfolio", // Update with your GitHub URL
  instagram: "https://www.instagram.com/", // Update with your Instagram URL
  linkedin: "https://www.linkedin.com/", // Update with your LinkedIn URL
  email: "mailto:example@gmail.com", // Update with your email address
};
```

### Sitemap

Adjust the routes to match your portfolio’s navigation in **app/sitemap.ts** file for SEO optimization:

```
let routes = ["", "blog", "projects", "photos"].map((route) => ({ // Update routes according to your navbar
  url: `${BaseUrl}${route}`,
  lastModified: new Date().toISOString().split("T")[0],
}));
```

### Profile Photo

Update your profile photo by replacing the **public/profile.png** file with your image.

### Favicon

Update your favicon by replacing the **public/favicon.ico** file with your custom icon.

## Analytics

Nextfolio 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.

## Ready!

You'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**.

Your 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.
]]></content>
        <author>
            <name>Dibakar Mitra</name>
            <email>dibakarmitra07@gmail.com</email>
            <uri>https://www.dibakarmitra.com</uri>
        </author>
        <category label="Configuration" term="Configuration"/>
        <category label="Web development" term="Web development"/>
    </entry>
    <entry>
        <title type="html"><![CDATA[Getting Started with Next.js 14]]></title>
        <id>https://www.dibakarmitra.com/notes/getting-started-with-nextjs</id>
        <link href="https://www.dibakarmitra.com/notes/getting-started-with-nextjs"/>
        <updated>2024-03-15T00:00:00.000Z</updated>
        <content type="html"><![CDATA[
# Getting Started with Next.js 14

Next.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.

## Why Next.js?

Next.js provides an excellent developer experience with features like:

- Server Components
- App Router
- Server Actions
- Streaming
- Built-in SEO Optimization

## Getting Started

```bash
npx create-next-app@latest my-app
cd my-app
npm run dev
```

## Key Features

### 1. Server Components

Server Components allow you to write UI that can be rendered and cached on the server. This results in:

- Smaller bundle sizes
- Better initial page loads
- Improved SEO

### 2. App Router

The new App Router provides:

- Nested layouts
- Colocated components
- Simplified routing

## Conclusion

Next.js 14 makes it easier than ever to build performant web applications. Give it a try in your next project!
]]></content>
        <author>
            <name>Dibakar Mitra</name>
            <email>dibakarmitra07@gmail.com</email>
            <uri>https://www.dibakarmitra.com</uri>
        </author>
        <category label="Next.js" term="Next.js"/>
        <category label="React" term="React"/>
        <category label="Web Development" term="Web Development"/>
    </entry>
    <entry>
        <title type="html"><![CDATA[Mastering TypeScript in 2024]]></title>
        <id>https://www.dibakarmitra.com/notes/mastering-typescript</id>
        <link href="https://www.dibakarmitra.com/notes/mastering-typescript"/>
        <updated>2024-03-10T00:00:00.000Z</updated>
        <content type="html"><![CDATA[
# Mastering TypeScript in 2024

TypeScript has become the go-to language for building scalable JavaScript applications. Let's dive into some advanced concepts.

## Type System Fundamentals

TypeScript's type system is powerful and flexible:

```typescript
// Basic Types
let name: string = 'John';
let age: number = 30;
let isActive: boolean = true;

// Union Types
type Status = 'pending' | 'active' | 'completed';
let taskStatus: Status = 'pending';

// Interfaces
interface User {
  id: number;
  name: string;
  email: string;
  role?: string;
}
```

## Advanced Features

### Generics

Generics make your code more reusable:

```typescript
function getFirst<T>(array: T[]): T | undefined {
  return array[0];
}

const first = getFirst([1, 2, 3]); // number
const firstString = getFirst(['a', 'b', 'c']); // string
```

### Utility Types

TypeScript provides built-in utility types:

```typescript
interface Todo {
  title: string;
  description: string;
  completed: boolean;
}

type TodoPreview = Pick<Todo, 'title' | 'completed'>;
type ReadonlyTodo = Readonly<Todo>;
```

## Best Practices

1. Always use strict mode
2. Leverage type inference
3. Use interfaces for object shapes
4. Implement proper error handling

## Conclusion

TypeScript continues to evolve and improve. Stay updated with the latest features to write better, safer code!
]]></content>
        <author>
            <name>Dibakar Mitra</name>
            <email>dibakarmitra07@gmail.com</email>
            <uri>https://www.dibakarmitra.com</uri>
        </author>
        <category label="TypeScript" term="TypeScript"/>
        <category label="JavaScript" term="JavaScript"/>
        <category label="Programming" term="Programming"/>
    </entry>
    <entry>
        <title type="html"><![CDATA[Advanced Tailwind CSS Tips and Tricks]]></title>
        <id>https://www.dibakarmitra.com/notes/tailwind-css-tips</id>
        <link href="https://www.dibakarmitra.com/notes/tailwind-css-tips"/>
        <updated>2024-03-01T00:00:00.000Z</updated>
        <content type="html"><![CDATA[
# Advanced Tailwind CSS Tips and Tricks

Tailwind CSS has transformed the way we style web applications. Here are some advanced techniques to level up your Tailwind game.

## Custom Configurations

Extend Tailwind's default configuration:

```javascript
// tailwind.config.js
module.exports = {
  theme: {
    extend: {
      colors: {
        primary: {
          50: '#f0f9ff',
          100: '#e0f2fe',
          // ... other shades
        }
      },
      spacing: {
        '128': '32rem',
      }
    }
  }
}
```

## Responsive Design Patterns

### Stack Pattern

```html
<div class="space-y-4 md:space-y-0 md:grid md:grid-cols-2 md:gap-6">
  <div class="p-4 bg-white shadow rounded">Item 1</div>
  <div class="p-4 bg-white shadow rounded">Item 2</div>
</div>
```

### Sidebar Pattern

```html
<div class="lg:grid lg:grid-cols-[300px_1fr] lg:gap-8">
  <nav class="hidden lg:block">Sidebar</nav>
  <main>Main Content</main>
</div>
```

## Animation Classes

```html
<button class="transform transition hover:scale-105 active:scale-95">
  Animated Button
</button>

<div class="animate-bounce">
  Bouncing Element
</div>
```

## Dark Mode

```html
<div class="bg-white dark:bg-gray-800 text-gray-900 dark:text-white">
  Automatic dark mode support
</div>
```

## Best Practices

1. Use consistent spacing scales
2. Leverage component classes
3. Utilize container queries
4. Implement proper responsive breakpoints

## Conclusion

Tailwind CSS provides powerful tools for building modern interfaces. Keep experimenting with these techniques to create better user experiences!
]]></content>
        <author>
            <name>Dibakar Mitra</name>
            <email>dibakarmitra07@gmail.com</email>
            <uri>https://www.dibakarmitra.com</uri>
        </author>
        <category label="Tailwind CSS" term="Tailwind CSS"/>
        <category label="CSS" term="CSS"/>
        <category label="Web Design" term="Web Design"/>
        <category label="Frontend" term="Frontend"/>
    </entry>
    <entry>
        <title type="html"><![CDATA[React Performance Optimization Techniques]]></title>
        <id>https://www.dibakarmitra.com/notes/react-performance-optimization</id>
        <link href="https://www.dibakarmitra.com/notes/react-performance-optimization"/>
        <updated>2024-02-25T00:00:00.000Z</updated>
        <content type="html"><![CDATA[
# React Performance Optimization Techniques

Performance optimization is crucial for creating smooth, responsive React applications. Let's explore some advanced techniques.

## 1. Memoization

### Using useMemo

```jsx
const memoizedValue = useMemo(() => computeExpensiveValue(a, b), [a, b]);
```

### Using React.memo

```jsx
const MyComponent = React.memo(function MyComponent(props) {
  return <div>{props.data}</div>;
});
```

## 2. Code Splitting

```jsx
const MyComponent = lazy(() => import('./MyComponent'));

function App() {
  return (
    <Suspense fallback={<Loading />}>
      <MyComponent />
    </Suspense>
  );
}
```

## 3. Virtual Lists

For long lists, use virtualization:

```jsx
import { FixedSizeList } from 'react-window';

function Row({ index, style }) {
  return <div style={style}>Row {index}</div>;
}

function List({ items }) {
  return (
    <FixedSizeList
      height={400}
      width={300}
      itemCount={items.length}
      itemSize={35}
    >
      {Row}
    </FixedSizeList>
  );
}
```

## 4. Debouncing and Throttling

```jsx
import { debounce } from 'lodash';

function SearchComponent() {
  const debouncedSearch = debounce((query) => {
    // API call
  }, 300);

  return <input onChange={(e) => debouncedSearch(e.target.value)} />;
}
```

## Best Practices

1. Use Production Builds
2. Implement Progressive Loading
3. Optimize Images and Assets
4. Monitor Bundle Size

## Conclusion

Performance optimization is an ongoing process. Regular profiling and monitoring help maintain optimal application performance.
]]></content>
        <author>
            <name>Dibakar Mitra</name>
            <email>dibakarmitra07@gmail.com</email>
            <uri>https://www.dibakarmitra.com</uri>
        </author>
        <category label="React" term="React"/>
        <category label="Performance" term="Performance"/>
        <category label="JavaScript" term="JavaScript"/>
        <category label="Web Development" term="Web Development"/>
    </entry>
    <entry>
        <title type="html"><![CDATA[Modern CSS Techniques for Better Web Design]]></title>
        <id>https://www.dibakarmitra.com/notes/modern-css-techniques</id>
        <link href="https://www.dibakarmitra.com/notes/modern-css-techniques"/>
        <updated>2024-02-20T00:00:00.000Z</updated>
        <content type="html"><![CDATA[
# Modern CSS Techniques for Better Web Design

CSS has evolved significantly in recent years. Let's explore some modern techniques that can enhance your web designs.

## CSS Grid Layout

Create complex layouts with minimal markup:

```css
.grid-container {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
  gap: 1rem;
}
```

## CSS Custom Properties (Variables)

```css
:root {
  --primary-color: #3490dc;
  --spacing-unit: 1rem;
}

.card {
  background: var(--primary-color);
  padding: var(--spacing-unit);
}

@media (prefers-color-scheme: dark) {
  :root {
    --primary-color: #64b5f6;
  }
}
```

## Container Queries

```css
.card {
  container-type: inline-size;
}

@container (min-width: 400px) {
  .card-content {
    display: grid;
    grid-template-columns: 2fr 1fr;
  }
}
```

## Modern Selectors

```css
/* Has selector */
.card:has(img) {
  padding: 0;
}

/* Not selector */
.card:not(:first-child) {
  margin-top: 1rem;
}

/* Where selector */
:where(.card, .box) {
  border-radius: 0.5rem;
}
```

## CSS Scroll Snap

```css
.scroll-container {
  scroll-snap-type: x mandatory;
  overflow-x: scroll;
}

.scroll-item {
  scroll-snap-align: start;
}
```

## CSS Animations

```css
@keyframes slide-in {
  from {
    transform: translateX(-100%);
    opacity: 0;
  }
  to {
    transform: translateX(0);
    opacity: 1;
  }
}

.animate-slide {
  animation: slide-in 0.5s ease-out;
}
```

## Best Practices

1. Use Logical Properties
2. Implement Progressive Enhancement
3. Consider Accessibility
4. Optimize Performance

## Conclusion

Modern CSS provides powerful tools for creating sophisticated web designs. Keep exploring these features to enhance your development workflow!
]]></content>
        <author>
            <name>Dibakar Mitra</name>
            <email>dibakarmitra07@gmail.com</email>
            <uri>https://www.dibakarmitra.com</uri>
        </author>
        <category label="CSS" term="CSS"/>
        <category label="Web Design" term="Web Design"/>
        <category label="Frontend" term="Frontend"/>
        <category label="Responsive Design" term="Responsive Design"/>
    </entry>
    <entry>
        <title type="html"><![CDATA[Modern Web Animation Techniques]]></title>
        <id>https://www.dibakarmitra.com/notes/web-animation-techniques</id>
        <link href="https://www.dibakarmitra.com/notes/web-animation-techniques"/>
        <updated>2024-02-20T00:00:00.000Z</updated>
        <content type="html"><![CDATA[
# Modern Web Animation Techniques

Creating smooth, performant animations is crucial for modern web applications. Let's explore various techniques and best practices.

## CSS Animations

### Basic Keyframe Animations

```css
@keyframes slideIn {
  from {
    transform: translateX(-100%);
    opacity: 0;
  }
  to {
    transform: translateX(0);
    opacity: 1;
  }
}

.slide-in {
  animation: slideIn 0.3s ease-out forwards;
}
```

### CSS Transitions

```css
.button {
  transition: transform 0.2s ease-in-out;
}

.button:hover {
  transform: scale(1.05);
}
```

## JavaScript Animations

### Web Animations API

```javascript
element.animate([
  { transform: 'scale(1)', opacity: 1 },
  { transform: 'scale(1.5)', opacity: 0 }
], {
  duration: 300,
  easing: 'ease-in-out',
  fill: 'forwards'
});
```

### RequestAnimationFrame

```javascript
function animate(element) {
  let start;

  function step(timestamp) {
    if (!start) start = timestamp;
    const progress = timestamp - start;

    element.style.transform = `translateX(${Math.min(progress / 10, 200)}px)`;

    if (progress < 2000) {
      requestAnimationFrame(step);
    }
  }

  requestAnimationFrame(step);
}
```

## Animation Libraries

### Framer Motion

```jsx
import { motion } from 'framer-motion';

function AnimatedComponent() {
  return (
    <motion.div
      initial={{ opacity: 0, y: 20 }}
      animate={{ opacity: 1, y: 0 }}
      transition={{ duration: 0.5 }}
    >
      Smooth entrance!
    </motion.div>
  );
}
```

### GSAP (GreenSock)

```javascript
import gsap from 'gsap';

gsap.to('.element', {
  duration: 1,
  x: 100,
  y: 50,
  rotation: 360,
  ease: 'power2.inOut'
});
```

## Performance Optimization

1. **Use Transform and Opacity**
   - These properties are GPU-accelerated
   - Avoid animating layout properties

2. **Debounce and Throttle**
   ```javascript
   function debounce(func, wait) {
     let timeout;
     return function executedFunction(...args) {
       const later = () => {
         clearTimeout(timeout);
         func(...args);
       };
       clearTimeout(timeout);
       timeout = setTimeout(later, wait);
     };
   }
   ```

3. **Will-change Property**
   ```css
   .animated-element {
     will-change: transform;
   }
   ```

## Accessibility Considerations

1. **Respect User Preferences**
   ```css
   @media (prefers-reduced-motion: reduce) {
     * {
       animation-duration: 0.01ms !important;
       animation-iteration-count: 1 !important;
       transition-duration: 0.01ms !important;
       scroll-behavior: auto !important;
     }
   }
   ```

2. **ARIA Labels**
   ```html
   <div 
     role="alert"
     aria-live="polite"
     className="animated-notification"
   >
     New message received
   </div>
   ```

## Best Practices

1. Keep animations subtle and purposeful
2. Use appropriate timing functions
3. Consider mobile performance
4. Test across different browsers
5. Implement fallbacks for older browsers

## Conclusion

Modern 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.]]></content>
        <author>
            <name>Dibakar Mitra</name>
            <email>dibakarmitra07@gmail.com</email>
            <uri>https://www.dibakarmitra.com</uri>
        </author>
        <category label="Animation" term="Animation"/>
        <category label="CSS" term="CSS"/>
        <category label="JavaScript" term="JavaScript"/>
        <category label="Web Development" term="Web Development"/>
    </entry>
    <entry>
        <title type="html"><![CDATA[GraphQL Best Practices and Advanced Patterns]]></title>
        <id>https://www.dibakarmitra.com/notes/graphql-best-practices</id>
        <link href="https://www.dibakarmitra.com/notes/graphql-best-practices"/>
        <updated>2024-02-15T00:00:00.000Z</updated>
        <content type="html"><![CDATA[
# GraphQL Best Practices and Advanced Patterns

GraphQL has transformed how we build APIs. Let's explore advanced patterns and best practices.

## Schema Design

### Type Definitions

```graphql
type User {
  id: ID!
  name: String!
  email: String!
  posts: [Post!]!
  profile: Profile
}

type Post {
  id: ID!
  title: String!
  content: String!
  author: User!
  comments: [Comment!]!
}

type Profile {
  bio: String
  avatar: String
  socialLinks: [SocialLink!]
}
```

## Query Optimization

### Field Selection

```graphql
query GetUserWithPosts {
  user(id: "123") {
    name
    posts(first: 5) {
      title
      comments {
        content
      }
    }
  }
}
```

### Using Fragments

```graphql
fragment UserFields on User {
  id
  name
  email
}

query GetUsers {
  users {
    ...UserFields
    posts {
      title
    }
  }
}
```

## Mutations

### Input Types

```graphql
input CreatePostInput {
  title: String!
  content: String!
  tags: [String!]
}

type Mutation {
  createPost(input: CreatePostInput!): Post!
}
```

## Error Handling

```graphql
type Error {
  message: String!
  code: String!
  path: [String!]
}

type PostResult {
  success: Boolean!
  post: Post
  errors: [Error!]
}

type Mutation {
  createPost(input: CreatePostInput!): PostResult!
}
```

## N+1 Problem Solution

```typescript
const resolvers = {
  User: {
    posts: async (parent, args, context, info) => {
      return context.dataloaders.posts.load(parent.id);
    }
  }
};
```

## Best Practices

1. Use DataLoaders for Batching
2. Implement Proper Pagination
3. Consider Query Complexity
4. Cache Effectively

## Security Considerations

1. Rate Limiting
2. Query Depth Limiting
3. Field Authorization
4. Input Validation

## Conclusion

GraphQL provides powerful tools for building flexible APIs. Following these patterns ensures scalable and maintainable applications.
]]></content>
        <author>
            <name>Dibakar Mitra</name>
            <email>dibakarmitra07@gmail.com</email>
            <uri>https://www.dibakarmitra.com</uri>
        </author>
        <category label="GraphQL" term="GraphQL"/>
        <category label="API" term="API"/>
        <category label="Backend" term="Backend"/>
        <category label="Web Development" term="Web Development"/>
    </entry>
    <entry>
        <title type="html"><![CDATA[Web3 Development Guide: Building for the Decentralized Web]]></title>
        <id>https://www.dibakarmitra.com/notes/web3-development-guide</id>
        <link href="https://www.dibakarmitra.com/notes/web3-development-guide"/>
        <updated>2024-02-15T00:00:00.000Z</updated>
        <content type="html"><![CDATA[
# Web3 Development Guide: Building for the Decentralized Web

Web3 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.

## Understanding Web3 Fundamentals

### What is Web3?

Web3 refers to a decentralized version of the internet built on blockchain technology. Key characteristics include:

- Decentralization
- Trustless systems
- Native payments
- User ownership
- Permissionless access

### Core Technologies

1. **Blockchain**
   - Distributed ledger technology
   - Consensus mechanisms
   - Cryptographic security

2. **Smart Contracts**
   - Self-executing contracts
   - Automated transactions
   - Decentralized logic

## Getting Started with Web3 Development

### Setting Up Your Development Environment

```bash
# Install Node.js and npm
npm install -g truffle
npm install -g ganache-cli

# Install MetaMask browser extension
# Create a new wallet and save the seed phrase
```

### Essential Tools

1. **Development Frameworks**
   - Truffle
   - Hardhat
   - Brownie (Python)

2. **Testing Networks**
   - Ganache
   - Testnet (Rinkeby, Ropsten)
   - Local blockchain

## Smart Contract Development

### Writing Your First Smart Contract

```solidity
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

contract SimpleStorage {
    uint256 private storedData;
    
    function set(uint256 x) public {
        storedData = x;
    }
    
    function get() public view returns (uint256) {
        return storedData;
    }
}
```

### Testing Smart Contracts

```javascript
const SimpleStorage = artifacts.require("SimpleStorage");

contract("SimpleStorage", accounts => {
  it("should store the value 89", async () => {
    const instance = await SimpleStorage.deployed();
    await instance.set(89);
    const storedData = await instance.get();
    assert.equal(storedData, 89);
  });
});
```

## Building Decentralized Applications (dApps)

### Frontend Integration

```javascript
// Using ethers.js
import { ethers } from 'ethers';

async function connectWallet() {
  if (typeof window.ethereum !== 'undefined') {
    try {
      await window.ethereum.request({ method: 'eth_requestAccounts' });
      const provider = new ethers.providers.Web3Provider(window.ethereum);
      const signer = provider.getSigner();
      return signer;
    } catch (error) {
      console.error("User denied account access");
    }
  }
}
```

### Interacting with Smart Contracts

```javascript
const contract = new ethers.Contract(
  contractAddress,
  contractABI,
  signer
);

async function setValue(value) {
  try {
    const tx = await contract.set(value);
    await tx.wait();
    console.log("Value set successfully");
  } catch (error) {
    console.error("Error:", error);
  }
}
```

## Web3 Security Best Practices

1. **Smart Contract Security**
   - Audit your contracts
   - Use established patterns
   - Test thoroughly
   - Consider gas optimization

2. **Frontend Security**
   - Validate user input
   - Secure key management
   - Handle errors gracefully

## Advanced Topics

### 1. DeFi Development

```solidity
contract Token is ERC20 {
    constructor(uint256 initialSupply) ERC20("MyToken", "MTK") {
        _mint(msg.sender, initialSupply);
    }
}
```

### 2. NFT Development

```solidity
contract NFT is ERC721 {
    constructor() ERC721("MyNFT", "MNFT") {}
    
    function mint(address to, uint256 tokenId) public {
        _safeMint(to, tokenId);
    }
}
```

### 3. DAOs and Governance

```solidity
contract DAO {
    struct Proposal {
        string description;
        uint256 voteCount;
        bool executed;
    }
    
    mapping(uint256 => Proposal) public proposals;
}
```

## Tools and Resources

1. **Development Tools**
   - Remix IDE
   - Web3.js
   - Ethers.js
   - OpenZeppelin

2. **Testing and Deployment**
   - Infura
   - Alchemy
   - IPFS

## Best Practices

1. **Code Quality**
   - Follow Solidity style guide
   - Document your code
   - Use design patterns

2. **Gas Optimization**
   - Minimize storage operations
   - Batch operations
   - Use appropriate data types

3. **User Experience**
   - Handle network changes
   - Provide clear feedback
   - Implement proper error handling

## Conclusion

Web3 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.]]></content>
        <author>
            <name>Dibakar Mitra</name>
            <email>dibakarmitra07@gmail.com</email>
            <uri>https://www.dibakarmitra.com</uri>
        </author>
        <category label="Web3" term="Web3"/>
        <category label="Blockchain" term="Blockchain"/>
        <category label="Ethereum" term="Ethereum"/>
        <category label="Smart Contracts" term="Smart Contracts"/>
        <category label="DApp" term="DApp"/>
    </entry>
    <entry>
        <title type="html"><![CDATA[Docker and Microservices Architecture]]></title>
        <id>https://www.dibakarmitra.com/notes/docker-microservices</id>
        <link href="https://www.dibakarmitra.com/notes/docker-microservices"/>
        <updated>2024-02-10T00:00:00.000Z</updated>
        <content type="html"><![CDATA[
# Docker and Microservices Architecture

Learn how to build and deploy scalable microservices using Docker and modern container orchestration tools.

## Docker Basics

### Dockerfile Example

```dockerfile
FROM node:18-alpine

WORKDIR /app

COPY package*.json ./
RUN npm install

COPY . .

EXPOSE 3000
CMD ["npm", "start"]
```

## Docker Compose

```yaml
version: '3.8'
services:
  api:
    build: ./api
    ports:
      - "3000:3000"
    environment:
      - DATABASE_URL=postgres://user:pass@db:5432/mydb
    depends_on:
      - db
  
  db:
    image: postgres:14
    environment:
      - POSTGRES_USER=user
      - POSTGRES_PASSWORD=pass
      - POSTGRES_DB=mydb
```

## Microservices Communication

### API Gateway Pattern

```typescript
// API Gateway
app.get('/orders/:id', async (req, res) => {
  const orderId = req.params.id;
  const order = await orderService.getOrder(orderId);
  const user = await userService.getUser(order.userId);
  const payment = await paymentService.getPayment(order.paymentId);
  
  res.json({
    ...order,
    user,
    payment
  });
});
```

## Service Discovery

```yaml
apiVersion: v1
kind: Service
metadata:
  name: api-service
spec:
  selector:
    app: api
  ports:
    - protocol: TCP
      port: 80
      targetPort: 3000
  type: LoadBalancer
```

## Best Practices

1. Use Multi-Stage Builds
2. Implement Health Checks
3. Follow the Twelve-Factor App Methodology
4. Implement Circuit Breakers

## Monitoring and Logging

```yaml
# Prometheus configuration
scrape_configs:
  - job_name: 'api'
    static_configs:
      - targets: ['api:3000']
```

## Security Best Practices

1. Use Minimal Base Images
2. Implement Least Privilege
3. Scan for Vulnerabilities
4. Secure Service Communication

## Conclusion

Docker and microservices provide a powerful foundation for building scalable applications. Remember to focus on security, monitoring, and maintainability.
]]></content>
        <author>
            <name>Dibakar Mitra</name>
            <email>dibakarmitra07@gmail.com</email>
            <uri>https://www.dibakarmitra.com</uri>
        </author>
        <category label="Docker" term="Docker"/>
        <category label="Microservices" term="Microservices"/>
        <category label="DevOps" term="DevOps"/>
        <category label="Kubernetes" term="Kubernetes"/>
    </entry>
    <entry>
        <title type="html"><![CDATA[Modern Testing Practices in Web Development]]></title>
        <id>https://www.dibakarmitra.com/notes/modern-testing-practices</id>
        <link href="https://www.dibakarmitra.com/notes/modern-testing-practices"/>
        <updated>2024-02-05T00:00:00.000Z</updated>
        <content type="html"><![CDATA[
# Modern Testing Practices in Web Development

Effective testing is crucial for maintaining code quality and preventing regressions. Let's explore modern testing approaches.

## Unit Testing with Jest

### Testing React Components

```jsx
import { render, screen, fireEvent } from '@testing-library/react';
import Counter from './Counter';

describe('Counter Component', () => {
  test('increments counter on button click', () => {
    render(<Counter />);
    const button = screen.getByRole('button', { name: /increment/i });
    const count = screen.getByText(/count:/i);
    
    expect(count).toHaveTextContent('Count: 0');
    fireEvent.click(button);
    expect(count).toHaveTextContent('Count: 1');
  });
});
```

## Integration Testing

```typescript
describe('UserService', () => {
  let userService: UserService;
  let dbConnection: Database;

  beforeEach(async () => {
    dbConnection = await createTestDatabase();
    userService = new UserService(dbConnection);
  });

  test('creates and retrieves user', async () => {
    const userData = {
      name: 'John Doe',
      email: 'john@example.com'
    };

    const user = await userService.createUser(userData);
    const retrieved = await userService.getUserById(user.id);

    expect(retrieved).toMatchObject(userData);
  });
});
```

## E2E Testing with Cypress

```javascript
describe('Shopping Cart', () => {
  beforeEach(() => {
    cy.visit('/');
    cy.login();
  });

  it('adds item to cart', () => {
    cy.get('[data-testid="product-item"]').first().click();
    cy.get('[data-testid="add-to-cart"]').click();
    cy.get('[data-testid="cart-count"]').should('have.text', '1');
  });

  it('completes checkout process', () => {
    cy.addItemToCart();
    cy.get('[data-testid="checkout"]').click();
    cy.fillShippingDetails();
    cy.get('[data-testid="submit-order"]').click();
    cy.url().should('include', '/order-confirmation');
  });
});
```

## API Testing

```typescript
import supertest from 'supertest';
import app from './app';

describe('API Endpoints', () => {
  const request = supertest(app);

  test('GET /api/users returns users list', async () => {
    const response = await request
      .get('/api/users')
      .expect('Content-Type', /json/)
      .expect(200);

    expect(response.body).toBeInstanceOf(Array);
  });

  test('POST /api/users creates new user', async () => {
    const userData = {
      name: 'Jane Doe',
      email: 'jane@example.com'
    };

    const response = await request
      .post('/api/users')
      .send(userData)
      .expect(201);

    expect(response.body).toMatchObject(userData);
  });
});
```

## Test Coverage

```javascript
// jest.config.js
module.exports = {
  collectCoverage: true,
  coverageThreshold: {
    global: {
      branches: 80,
      functions: 80,
      lines: 80,
      statements: 80
    }
  }
};
```

## Best Practices

1. Follow the Testing Pyramid
2. Write Maintainable Tests
3. Use Test Doubles Appropriately
4. Implement Continuous Integration

## Testing Strategies

1. Test-Driven Development (TDD)
2. Behavior-Driven Development (BDD)
3. Property-Based Testing
4. Visual Regression Testing

## Conclusion

Effective testing is an investment in code quality and team productivity. Choose the right testing strategies and tools for your project's needs.
]]></content>
        <author>
            <name>Dibakar Mitra</name>
            <email>dibakarmitra07@gmail.com</email>
            <uri>https://www.dibakarmitra.com</uri>
        </author>
        <category label="Testing" term="Testing"/>
        <category label="Jest" term="Jest"/>
        <category label="Cypress" term="Cypress"/>
        <category label="TDD" term="TDD"/>
    </entry>
    <entry>
        <title type="html"><![CDATA[Modern State Management Patterns in React]]></title>
        <id>https://www.dibakarmitra.com/notes/state-management-patterns</id>
        <link href="https://www.dibakarmitra.com/notes/state-management-patterns"/>
        <updated>2024-01-30T00:00:00.000Z</updated>
        <content type="html"><![CDATA[
# Modern State Management Patterns in React

State management is a crucial aspect of modern web applications. Let's explore different patterns and solutions.

## React Context API

```tsx
// Create context
const ThemeContext = createContext<{
  theme: string;
  setTheme: (theme: string) => void;
}>({
  theme: 'light',
  setTheme: () => {}
});

// Provider component
export function ThemeProvider({ children }: { children: React.ReactNode }) {
  const [theme, setTheme] = useState('light');

  return (
    <ThemeContext.Provider value={{ theme, setTheme }}>
      {children}
    </ThemeContext.Provider>
  );
}

// Usage in components
function ThemeToggle() {
  const { theme, setTheme } = useContext(ThemeContext);
  
  return (
    <button onClick={() => setTheme(theme === 'light' ? 'dark' : 'light')}>
      Toggle Theme
    </button>
  );
}
```

## Redux Toolkit

```typescript
// Store slice
import { createSlice, PayloadAction } from '@reduxjs/toolkit';

interface CartState {
  items: CartItem[];
  total: number;
}

const cartSlice = createSlice({
  name: 'cart',
  initialState: { items: [], total: 0 } as CartState,
  reducers: {
    addItem: (state, action: PayloadAction<CartItem>) => {
      state.items.push(action.payload);
      state.total += action.payload.price;
    },
    removeItem: (state, action: PayloadAction<string>) => {
      const item = state.items.find(item => item.id === action.payload);
      if (item) {
        state.total -= item.price;
        state.items = state.items.filter(item => item.id !== action.payload);
      }
    }
  }
});

// Usage in components
function CartComponent() {
  const cart = useSelector((state: RootState) => state.cart);
  const dispatch = useDispatch();

  return (
    <div>
      <h2>Cart Total: ${cart.total}</h2>
      {cart.items.map(item => (
        <div key={item.id}>
          <span>{item.name}</span>
          <button onClick={() => dispatch(removeItem(item.id))}>
            Remove
          </button>
        </div>
      ))}
    </div>
  );
}
```

## Zustand

```typescript
import create from 'zustand';

interface UserStore {
  user: User | null;
  setUser: (user: User | null) => void;
  logout: () => void;
}

const useUserStore = create<UserStore>((set) => ({
  user: null,
  setUser: (user) => set({ user }),
  logout: () => set({ user: null })
}));

// Usage
function UserProfile() {
  const { user, logout } = useUserStore();

  if (!user) return <LoginButton />;

  return (
    <div>
      <h2>Welcome, {user.name}</h2>
      <button onClick={logout}>Logout</button>
    </div>
  );
}
```

## Jotai

```typescript
import { atom, useAtom } from 'jotai';

const counterAtom = atom(0);
const doubleAtom = atom((get) => get(counterAtom) * 2);

function Counter() {
  const [count, setCount] = useAtom(counterAtom);
  const [double] = useAtom(doubleAtom);

  return (
    <div>
      <h2>Count: {count}</h2>
      <h3>Double: {double}</h3>
      <button onClick={() => setCount(c => c + 1)}>
        Increment
      </button>
    </div>
  );
}
```

## Best Practices

1. Choose the Right Tool
   - Small apps: React Context/useState
   - Medium apps: Zustand/Jotai
   - Large apps: Redux Toolkit

2. State Organization
   - Keep state close to where it's used
   - Split global state into domains
   - Use selectors for derived state

3. Performance Optimization
   - Memoize selectors
   - Use context splitting
   - Implement proper re-render prevention

## Common Patterns

### Command Pattern

```typescript
type Command = {
  type: string;
  payload?: any;
};

function commandReducer(state: State, command: Command) {
  switch (command.type) {
    case 'ADD_ITEM':
      return {
        ...state,
        items: [...state.items, command.payload]
      };
    // ... other cases
  }
}
```

### Observer Pattern

```typescript
const createStore = <T>(initialState: T) => {
  let state = initialState;
  const listeners = new Set<(state: T) => void>();

  return {
    getState: () => state,
    setState: (newState: T) => {
      state = newState;
      listeners.forEach(listener => listener(state));
    },
    subscribe: (listener: (state: T) => void) => {
      listeners.add(listener);
      return () => listeners.delete(listener);
    }
  };
};
```

## Conclusion

Choose the right state management solution based on your application's needs. Consider factors like team size, application complexity, and performance requirements.
]]></content>
        <author>
            <name>Dibakar Mitra</name>
            <email>dibakarmitra07@gmail.com</email>
            <uri>https://www.dibakarmitra.com</uri>
        </author>
        <category label="React" term="React"/>
        <category label="State Management" term="State Management"/>
        <category label="Redux" term="Redux"/>
        <category label="Zustand" term="Zustand"/>
    </entry>
    <entry>
        <title type="html"><![CDATA[Web Accessibility Guide: Building Inclusive Applications]]></title>
        <id>https://www.dibakarmitra.com/notes/web-accessibility-guide</id>
        <link href="https://www.dibakarmitra.com/notes/web-accessibility-guide"/>
        <updated>2024-01-20T00:00:00.000Z</updated>
        <content type="html"><![CDATA[
# Web Accessibility Guide: Building Inclusive Applications

Creating accessible web applications is not just a legal requirement but a moral imperative. Let's explore how to make our applications work for everyone.

## Semantic HTML

```html
<!-- Bad -->
<div class="button" onclick="submit()">
  Submit Form
</div>

<!-- Good -->
<button type="submit" aria-label="Submit form">
  Submit Form
</button>

<!-- Bad -->
<div class="header">
  <div class="nav">...</div>
</div>

<!-- Good -->
<header>
  <nav aria-label="Main navigation">...</nav>
</header>
```

## ARIA Attributes

```jsx
// React component with ARIA attributes
function Accordion({ items }) {
  const [activeIndex, setActiveIndex] = useState(null);

  return (
    <div role="region" aria-label="FAQ Accordion">
      {items.map((item, index) => (
        <div key={index}>
          <button
            aria-expanded={activeIndex === index}
            aria-controls={`content-${index}`}
            onClick={() => setActiveIndex(index)}
          >
            {item.title}
          </button>
          <div
            id={`content-${index}`}
            role="region"
            aria-hidden={activeIndex !== index}
          >
            {item.content}
          </div>
        </div>
      ))}
    </div>
  );
}
```

## Focus Management

```typescript
function Modal({ isOpen, onClose, children }) {
  const modalRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    if (isOpen) {
      // Store the element that had focus before opening modal
      const previousFocus = document.activeElement;
      
      // Focus the modal
      modalRef.current?.focus();

      // Restore focus when modal closes
      return () => {
        (previousFocus as HTMLElement)?.focus();
      };
    }
  }, [isOpen]);

  return isOpen ? (
    <div
      ref={modalRef}
      role="dialog"
      aria-modal="true"
      tabIndex={-1}
      aria-labelledby="modal-title"
    >
      <h2 id="modal-title">Modal Title</h2>
      {children}
      <button onClick={onClose}>Close</button>
    </div>
  ) : null;
}
```

## Skip Links

```tsx
function SkipLink() {
  return (
    <a
      href="#main-content"
      className="skip-link"
      style={{
        position: 'absolute',
        top: -40,
        left: 0,
        padding: 8,
        zIndex: 100,
        ':focus': {
          top: 0,
        },
      }}
    >
      Skip to main content
    </a>
  );
}
```

## Color Contrast

```typescript
function isColorContrastValid(foreground: string, background: string): boolean {
  const luminance = (r: number, g: number, b: number) => {
    const [rs, gs, bs] = [r, g, b].map(c => {
      c = c / 255;
      return c <= 0.03928
        ? c / 12.92
        : Math.pow((c + 0.055) / 1.055, 2.4);
    });
    return 0.2126 * rs + 0.7152 * gs + 0.0722 * bs;
  };

  const hex2rgb = (hex: string) => {
    const result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
    return result
      ? [
          parseInt(result[1], 16),
          parseInt(result[2], 16),
          parseInt(result[3], 16),
        ]
      : null;
  };

  const fg = hex2rgb(foreground);
  const bg = hex2rgb(background);

  if (!fg || !bg) return false;

  const l1 = luminance(fg[0], fg[1], fg[2]);
  const l2 = luminance(bg[0], bg[1], bg[2]);

  const ratio = (Math.max(l1, l2) + 0.05) / (Math.min(l1, l2) + 0.05);
  return ratio >= 4.5; // WCAG AA standard for normal text
}
```

## Keyboard Navigation

```tsx
function KeyboardNavList({ items }) {
  const [selectedIndex, setSelectedIndex] = useState(0);

  const handleKeyDown = (event: React.KeyboardEvent) => {
    switch (event.key) {
      case 'ArrowDown':
        event.preventDefault();
        setSelectedIndex(i => Math.min(i + 1, items.length - 1));
        break;
      case 'ArrowUp':
        event.preventDefault();
        setSelectedIndex(i => Math.max(i - 1, 0));
        break;
    }
  };

  return (
    <ul role="listbox" onKeyDown={handleKeyDown}>
      {items.map((item, index) => (
        <li
          key={index}
          role="option"
          aria-selected={index === selectedIndex}
          tabIndex={index === selectedIndex ? 0 : -1}
        >
          {item.label}
        </li>
      ))}
    </ul>
  );
}
```

## Form Accessibility

```tsx
function AccessibleForm() {
  return (
    <form aria-labelledby="form-title">
      <h2 id="form-title">Contact Us</h2>
      
      <div>
        <label htmlFor="name">
          Name
          <span aria-hidden="true">*</span>
          <span className="sr-only">required</span>
        </label>
        <input
          id="name"
          type="text"
          required
          aria-required="true"
          aria-describedby="name-error"
        />
        <div id="name-error" role="alert"></div>
      </div>

      <div>
        <label htmlFor="email">Email</label>
        <input
          id="email"
          type="email"
          aria-describedby="email-hint"
        />
        <div id="email-hint" className="hint">
          We'll never share your email
        </div>
      </div>
    </form>
  );
}
```

## Best Practices

1. Semantic HTML
   - Use proper heading hierarchy
   - Use semantic elements
   - Provide alternative text for images

2. Keyboard Navigation
   - Ensure all interactive elements are focusable
   - Implement logical tab order
   - Provide visible focus indicators

3. ARIA Implementation
   - Use ARIA labels when needed
   - Implement proper roles
   - Manage dynamic content updates

4. Testing
   - Use screen readers
   - Keyboard navigation testing
   - Automated accessibility testing

## Conclusion

Accessibility should be considered from the start of development, not as an afterthought. Following these practices ensures your application is usable by everyone.
]]></content>
        <author>
            <name>Dibakar Mitra</name>
            <email>dibakarmitra07@gmail.com</email>
            <uri>https://www.dibakarmitra.com</uri>
        </author>
        <category label="Accessibility" term="Accessibility"/>
        <category label="WCAG" term="WCAG"/>
        <category label="Web Development" term="Web Development"/>
        <category label="UX" term="UX"/>
    </entry>
    <entry>
        <title type="html"><![CDATA[Advanced React Hooks: Beyond the Basics]]></title>
        <id>https://www.dibakarmitra.com/notes/advanced-react-hooks</id>
        <link href="https://www.dibakarmitra.com/notes/advanced-react-hooks"/>
        <updated>2024-01-15T00:00:00.000Z</updated>
        <content type="html"><![CDATA[
A comprehensive guide to advanced React hooks patterns, including custom hooks development, performance optimization, and best practices for state management.]]></content>
        <author>
            <name>Dibakar Mitra</name>
            <email>dibakarmitra07@gmail.com</email>
            <uri>https://www.dibakarmitra.com</uri>
        </author>
        <category label="react" term="react"/>
        <category label="hooks" term="hooks"/>
        <category label="javascript" term="javascript"/>
    </entry>
    <entry>
        <title type="html"><![CDATA[System Design Principles and Best Practices]]></title>
        <id>https://www.dibakarmitra.com/notes/system-design-principles</id>
        <link href="https://www.dibakarmitra.com/notes/system-design-principles"/>
        <updated>2024-01-15T00:00:00.000Z</updated>
        <content type="html"><![CDATA[
# System Design Principles and Best Practices

Understanding system design principles is crucial for building scalable, reliable applications. Let's explore key concepts and patterns.

## Load Balancing

```typescript
// Load Balancer Interface
interface LoadBalancer {
  addServer(server: Server): void;
  removeServer(server: Server): void;
  getNextServer(): Server;
}

// Round Robin Implementation
class RoundRobinLoadBalancer implements LoadBalancer {
  private servers: Server[] = [];
  private currentIndex = 0;

  addServer(server: Server): void {
    this.servers.push(server);
  }

  removeServer(server: Server): void {
    this.servers = this.servers.filter(s => s.id !== server.id);
  }

  getNextServer(): Server {
    if (this.servers.length === 0) {
      throw new Error('No servers available');
    }

    const server = this.servers[this.currentIndex];
    this.currentIndex = (this.currentIndex + 1) % this.servers.length;
    return server;
  }
}
```

## Caching Strategy

```typescript
interface Cache<K, V> {
  get(key: K): V | null;
  put(key: K, value: V): void;
  remove(key: K): void;
}

class LRUCache<K, V> implements Cache<K, V> {
  private capacity: number;
  private cache: Map<K, V>;
  private usage: Map<K, number>;
  private time: number = 0;

  constructor(capacity: number) {
    this.capacity = capacity;
    this.cache = new Map();
    this.usage = new Map();
  }

  get(key: K): V | null {
    const value = this.cache.get(key);
    if (value !== undefined) {
      this.usage.set(key, ++this.time);
      return value;
    }
    return null;
  }

  put(key: K, value: V): void {
    if (this.cache.size >= this.capacity && !this.cache.has(key)) {
      // Find least recently used item
      let lruKey = this.findLRU();
      this.cache.delete(lruKey);
      this.usage.delete(lruKey);
    }

    this.cache.set(key, value);
    this.usage.set(key, ++this.time);
  }

  remove(key: K): void {
    this.cache.delete(key);
    this.usage.delete(key);
  }

  private findLRU(): K {
    let minTime = Infinity;
    let lruKey: K = null!;
    
    this.usage.forEach((time, key) => {
      if (time < minTime) {
        minTime = time;
        lruKey = key;
      }
    });
    
    return lruKey;
  }
}
```

## Message Queue

```typescript
interface Message {
  id: string;
  payload: any;
  timestamp: number;
}

class MessageQueue {
  private queue: Message[] = [];
  private consumers: Set<(message: Message) => void> = new Set();

  publish(message: Message): void {
    this.queue.push(message);
    this.notifyConsumers(message);
  }

  subscribe(callback: (message: Message) => void): () => void {
    this.consumers.add(callback);
    return () => this.consumers.delete(callback);
  }

  private notifyConsumers(message: Message): void {
    this.consumers.forEach(callback => {
      try {
        callback(message);
      } catch (error) {
        console.error('Error processing message:', error);
      }
    });
  }
}
```

## Rate Limiting

```typescript
class TokenBucket {
  private tokens: number;
  private lastRefill: number;
  private readonly capacity: number;
  private readonly refillRate: number;

  constructor(capacity: number, refillRate: number) {
    this.capacity = capacity;
    this.refillRate = refillRate;
    this.tokens = capacity;
    this.lastRefill = Date.now();
  }

  consume(tokens: number = 1): boolean {
    this.refill();

    if (this.tokens >= tokens) {
      this.tokens -= tokens;
      return true;
    }

    return false;
  }

  private refill(): void {
    const now = Date.now();
    const timePassed = now - this.lastRefill;
    const tokensToAdd = (timePassed * this.refillRate) / 1000;

    this.tokens = Math.min(this.capacity, this.tokens + tokensToAdd);
    this.lastRefill = now;
  }
}
```

## Service Discovery

```typescript
interface ServiceRegistry {
  register(service: Service): void;
  unregister(serviceId: string): void;
  discover(serviceName: string): Service[];
}

class EtcdServiceRegistry implements ServiceRegistry {
  private services: Map<string, Service[]> = new Map();

  register(service: Service): void {
    const services = this.services.get(service.name) || [];
    services.push(service);
    this.services.set(service.name, services);
  }

  unregister(serviceId: string): void {
    this.services.forEach((services, name) => {
      const filtered = services.filter(s => s.id !== serviceId);
      if (filtered.length > 0) {
        this.services.set(name, filtered);
      } else {
        this.services.delete(name);
      }
    });
  }

  discover(serviceName: string): Service[] {
    return this.services.get(serviceName) || [];
  }
}
```

## Circuit Breaker

```typescript
enum CircuitState {
  CLOSED,
  OPEN,
  HALF_OPEN
}

class CircuitBreaker {
  private state: CircuitState = CircuitState.CLOSED;
  private failures: number = 0;
  private lastFailure: number = 0;
  private readonly threshold: number;
  private readonly timeout: number;

  constructor(threshold: number = 5, timeout: number = 60000) {
    this.threshold = threshold;
    this.timeout = timeout;
  }

  async execute<T>(
    action: () => Promise<T>,
    fallback: () => Promise<T>
  ): Promise<T> {
    if (this.state === CircuitState.OPEN) {
      if (Date.now() - this.lastFailure >= this.timeout) {
        this.state = CircuitState.HALF_OPEN;
      } else {
        return fallback();
      }
    }

    try {
      const result = await action();
      if (this.state === CircuitState.HALF_OPEN) {
        this.state = CircuitState.CLOSED;
        this.failures = 0;
      }
      return result;
    } catch (error) {
      this.failures++;
      this.lastFailure = Date.now();

      if (this.failures >= this.threshold) {
        this.state = CircuitState.OPEN;
      }

      return fallback();
    }
  }
}
```

## Best Practices

1. Scalability
   - Horizontal scaling
   - Database sharding
   - Caching strategies
   - Load balancing

2. Reliability
   - Circuit breakers
   - Retry mechanisms
   - Fallback strategies
   - Error handling

3. Maintainability
   - Service discovery
   - Configuration management
   - Monitoring and logging
   - Documentation

4. Performance
   - Caching
   - Connection pooling
   - Asynchronous processing
   - Resource optimization

## Conclusion

Effective system design requires careful consideration of scalability, reliability, and maintainability. These patterns and principles provide a foundation for building robust systems.
]]></content>
        <author>
            <name>Dibakar Mitra</name>
            <email>dibakarmitra07@gmail.com</email>
            <uri>https://www.dibakarmitra.com</uri>
        </author>
        <category label="System Design" term="System Design"/>
        <category label="Architecture" term="Architecture"/>
        <category label="Scalability" term="Scalability"/>
        <category label="Backend" term="Backend"/>
    </entry>
    <entry>
        <title type="html"><![CDATA[API Design Patterns and Best Practices]]></title>
        <id>https://www.dibakarmitra.com/notes/api-design-patterns</id>
        <link href="https://www.dibakarmitra.com/notes/api-design-patterns"/>
        <updated>2024-01-10T00:00:00.000Z</updated>
        <content type="html"><![CDATA[
# API Design Patterns and Best Practices

Designing good APIs is crucial for building maintainable and scalable applications. Let's explore best practices and patterns.

## RESTful API Design

### Resource Modeling

```typescript
// User Resource
interface User {
  id: string;
  name: string;
  email: string;
  role: UserRole;
  createdAt: Date;
  updatedAt: Date;
}

// API Endpoints
class UserController {
  // GET /users
  async listUsers(
    page: number = 1,
    limit: number = 10,
    sort?: string
  ): Promise<PaginatedResponse<User>> {
    // Implementation
  }

  // GET /users/:id
  async getUser(id: string): Promise<User> {
    // Implementation
  }

  // POST /users
  async createUser(data: CreateUserDTO): Promise<User> {
    // Implementation
  }

  // PATCH /users/:id
  async updateUser(id: string, data: UpdateUserDTO): Promise<User> {
    // Implementation
  }

  // DELETE /users/:id
  async deleteUser(id: string): Promise<void> {
    // Implementation
  }
}
```

## Response Handling

```typescript
interface ApiResponse<T> {
  data: T;
  meta?: {
    page?: number;
    limit?: number;
    total?: number;
  };
  links?: {
    self: string;
    next?: string;
    prev?: string;
  };
}

interface ApiError {
  code: string;
  message: string;
  details?: Record<string, any>;
}

// Example Response Handler
class ResponseHandler {
  static success<T>(data: T, meta?: any): ApiResponse<T> {
    return {
      data,
      meta,
      links: {
        self: getCurrentUrl()
      }
    };
  }

  static error(error: Error): ApiError {
    return {
      code: error.name,
      message: error.message,
      details: error instanceof ApiError ? error.details : undefined
    };
  }
}
```

## Validation

```typescript
import { z } from 'zod';

// Request Validation Schema
const CreateUserSchema = z.object({
  name: z.string().min(2).max(100),
  email: z.string().email(),
  password: z.string().min(8).regex(/[A-Z]/).regex(/[0-9]/),
  role: z.enum(['user', 'admin'])
});

// Middleware
function validateRequest(schema: z.Schema) {
  return async (req: Request, res: Response, next: NextFunction) => {
    try {
      req.body = await schema.parseAsync(req.body);
      next();
    } catch (error) {
      if (error instanceof z.ZodError) {
        res.status(400).json({
          code: 'VALIDATION_ERROR',
          message: 'Invalid request data',
          details: error.errors
        });
      } else {
        next(error);
      }
    }
  };
}
```

## Rate Limiting

```typescript
import rateLimit from 'express-rate-limit';
import Redis from 'ioredis';

class RateLimiter {
  private redis: Redis;
  private prefix: string;

  constructor(redisUrl: string, prefix: string = 'ratelimit:') {
    this.redis = new Redis(redisUrl);
    this.prefix = prefix;
  }

  createLimiter(options: {
    windowMs: number;
    max: number;
    keyGenerator?: (req: Request) => string;
  }) {
    return rateLimit({
      store: {
        increment: async (key: string) => {
          const redisKey = this.prefix + key;
          const multi = this.redis.multi();
          
          multi.incr(redisKey);
          multi.pexpire(redisKey, options.windowMs);
          
          const [count] = await multi.exec();
          return count?.[1] as number;
        },
        decrement: async (key: string) => {
          await this.redis.decr(this.prefix + key);
        },
        resetKey: async (key: string) => {
          await this.redis.del(this.prefix + key);
        }
      },
      ...options
    });
  }
}
```

## Versioning

```typescript
// Version through URL
// /api/v1/users

// Version through Accept header
app.use((req, res, next) => {
  const accept = req.get('Accept');
  if (accept?.includes('version=1')) {
    req.apiVersion = 1;
  } else if (accept?.includes('version=2')) {
    req.apiVersion = 2;
  } else {
    req.apiVersion = 1; // default version
  }
  next();
});

// Version-specific controllers
class UserControllerV1 {
  // V1 implementations
}

class UserControllerV2 extends UserControllerV1 {
  // V2 implementations with changes
  async listUsers(page: number = 1, limit: number = 10): Promise<User[]> {
    // New implementation
    return super.listUsers(page, limit);
  }
}
```

## Documentation

```typescript
/**
 * @api {post} /users Create User
 * @apiVersion 1.0.0
 * @apiName CreateUser
 * @apiGroup Users
 *
 * @apiParam {String} name User's full name
 * @apiParam {String} email User's email
 * @apiParam {String} password User's password
 * @apiParam {String="user","admin"} role User's role
 *
 * @apiSuccess {String} id User's unique ID
 * @apiSuccess {String} name User's name
 * @apiSuccess {String} email User's email
 * @apiSuccess {String} role User's role
 * @apiSuccess {Date} createdAt Creation timestamp
 *
 * @apiError {String} code Error code
 * @apiError {String} message Error message
 * @apiError {Object} details Validation details
 */
async createUser(req: Request, res: Response) {
  // Implementation
}
```

## GraphQL API Design

```typescript
import { gql } from 'apollo-server';

const typeDefs = gql`
  type User {
    id: ID!
    name: String!
    email: String!
    posts: [Post!]!
    profile: Profile
  }

  type Post {
    id: ID!
    title: String!
    content: String!
    author: User!
    comments: [Comment!]!
  }

  input CreateUserInput {
    name: String!
    email: String!
    password: String!
  }

  type Mutation {
    createUser(input: CreateUserInput!): User!
    updateUser(id: ID!, input: UpdateUserInput!): User!
    deleteUser(id: ID!): Boolean!
  }

  type Query {
    users(
      page: Int = 1
      limit: Int = 10
      sort: String
    ): UserConnection!
    user(id: ID!): User
  }
`;

const resolvers = {
  Query: {
    users: async (_, { page, limit, sort }, context) => {
      // Implementation with pagination
    },
    user: async (_, { id }, context) => {
      // Implementation
    }
  },
  Mutation: {
    createUser: async (_, { input }, context) => {
      // Implementation
    }
  }
};
```

## Best Practices

1. Resource Design
   - Use nouns for resources
   - Keep URLs consistent
   - Use proper HTTP methods
   - Implement HATEOAS

2. Security
   - Use HTTPS
   - Implement authentication
   - Rate limiting
   - Input validation

3. Performance
   - Implement caching
   - Use pagination
   - Support filtering
   - Enable compression

4. Documentation
   - OpenAPI/Swagger
   - Clear examples
   - Error documentation
   - Version documentation

## Conclusion

Good API design focuses on developer experience, maintainability, and scalability. Following these patterns and practices helps create robust and user-friendly APIs.
]]></content>
        <author>
            <name>Dibakar Mitra</name>
            <email>dibakarmitra07@gmail.com</email>
            <uri>https://www.dibakarmitra.com</uri>
        </author>
        <category label="API Design" term="API Design"/>
        <category label="REST" term="REST"/>
        <category label="GraphQL" term="GraphQL"/>
        <category label="Web Development" term="Web Development"/>
    </entry>
    <entry>
        <title type="html"><![CDATA[Database Design Patterns and Best Practices]]></title>
        <id>https://www.dibakarmitra.com/notes/database-design-patterns</id>
        <link href="https://www.dibakarmitra.com/notes/database-design-patterns"/>
        <updated>2024-01-05T00:00:00.000Z</updated>
        <content type="html"><![CDATA[
# Database Design Patterns and Best Practices

Effective database design is crucial for application performance and scalability. Let's explore key patterns and practices.

## Schema Design

### Relational Database Schema

```sql
-- Users Table
CREATE TABLE users (
    id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
    email VARCHAR(255) UNIQUE NOT NULL CHECK (email ~* '^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}$'),
    password_hash VARCHAR(255) NOT NULL,
    full_name VARCHAR(100) NOT NULL,
    created_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP
);

-- Posts Table
CREATE TABLE posts (
    id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
    user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
    title VARCHAR(200) NOT NULL,
    content TEXT NOT NULL,
    status VARCHAR(20) DEFAULT 'draft' CHECK (status IN ('draft', 'published', 'archived')),
    published_at TIMESTAMP WITH TIME ZONE,
    created_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP
);

-- Tags Table
CREATE TABLE tags (
    id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
    name VARCHAR(50) UNIQUE NOT NULL,
    created_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP
);

-- Posts Tags Junction Table
CREATE TABLE posts_tags (
    post_id UUID REFERENCES posts(id) ON DELETE CASCADE,
    tag_id UUID REFERENCES tags(id) ON DELETE CASCADE,
    PRIMARY KEY (post_id, tag_id)
);

-- Indexes
CREATE INDEX idx_users_email ON users(email);
CREATE INDEX idx_posts_user_id ON posts(user_id);
CREATE INDEX idx_posts_status ON posts(status);
CREATE INDEX idx_posts_published_at ON posts(published_at);
```

## NoSQL Schema Design

### MongoDB Schema

```typescript
import { ObjectId } from 'mongodb';

interface User {
  _id: ObjectId;
  email: string;
  passwordHash: string;
  fullName: string;
  profile: {
    bio: string;
    avatar: string;
    socialLinks: {
      platform: string;
      url: string;
    }[];
  };
  createdAt: Date;
  updatedAt: Date;
}

// MongoDB Schema Validation
db.createCollection("users", {
   validator: {
      $jsonSchema: {
         bsonType: "object",
         required: ["email", "passwordHash", "fullName"],
         properties: {
            email: {
               bsonType: "string",
               pattern: "^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,}$"
            }
         }
      }
   }
});

interface Post {
  _id: ObjectId;
  userId: ObjectId;
  title: string;
  content: string;
  status: 'draft' | 'published' | 'archived';
  tags: string[];
  comments: {
    userId: ObjectId;
    content: string;
    createdAt: Date;
  }[];
  metadata: {
    views: number;
    likes: number;
    shares: number;
  };
  publishedAt?: Date;
  createdAt: Date;
  updatedAt: Date;
}
```

## Query Optimization

### SQL Query Optimization

```sql
-- Using Indexes Effectively
EXPLAIN ANALYZE
SELECT p.*, u.full_name as author_name
FROM posts p
JOIN users u ON p.user_id = u.id
WHERE p.status = 'published'
  AND p.published_at >= NOW() - INTERVAL '7 days'
ORDER BY p.published_at DESC
LIMIT 10;

-- Optimized Query with Materialized View
CREATE MATERIALIZED VIEW recent_posts AS
SELECT 
    p.*,
    u.full_name as author_name,
    COUNT(c.id) as comment_count
FROM posts p
JOIN users u ON p.user_id = u.id
LEFT JOIN comments c ON p.id = c.post_id
WHERE p.status = 'published'
GROUP BY p.id, u.full_name
ORDER BY p.published_at DESC;

-- Refresh Materialized View
REFRESH MATERIALIZED VIEW recent_posts;
```

## Database Migrations

```typescript
import { MigrationInterface, QueryRunner } from 'typeorm';

export class AddUserProfileTable1641234567890 implements MigrationInterface {
  public async up(queryRunner: QueryRunner): Promise<void> {
    await queryRunner.query(`
      CREATE TABLE user_profiles (
        id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
        user_id UUID NOT NULL UNIQUE REFERENCES users(id) ON DELETE CASCADE,
        bio TEXT,
        avatar_url VARCHAR(255),
        location VARCHAR(100),
        created_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP,
        updated_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP
      );

      CREATE INDEX idx_user_profiles_user_id ON user_profiles(user_id);
    `);
  }

  public async down(queryRunner: QueryRunner): Promise<void> {
    await queryRunner.query(`
      DROP TABLE user_profiles;
    `);
  }
}
```

## Connection Pooling

```typescript
import { Pool, QueryResult } from 'pg';

interface DatabaseConfig {
  user: string;
  host: string;
  database: string;
  password: string;
  port: number;
  max: number;
  idleTimeoutMillis: number;
  connectionTimeoutMillis: number;
}

const config: DatabaseConfig = {
  user: process.env.DB_USER,
  host: process.env.DB_HOST,
  database: process.env.DB_NAME,
  password: process.env.DB_PASSWORD,
  port: parseInt(process.env.DB_PORT || '5432'),
  max: 20,
  idleTimeoutMillis: 30000,
  connectionTimeoutMillis: 2000,
};

const pool = new Pool(config);

// Error handling
pool.on('error', (err: Error) => {
  console.error('Unexpected error on idle client', err);
  process.exit(-1);
});

interface Post {
  id: string;
  user_id: string;
  title: string;
  content: string;
  status: 'draft' | 'published' | 'archived';
  published_at: Date | null;
  created_at: Date;
  updated_at: Date;
}

async function getUserPosts(userId: string): Promise<Post[]> {
  const client = await pool.connect();
  try {
    const result: QueryResult<Post> = await client.query(
      'SELECT * FROM posts WHERE user_id = $1',
      [userId]
    );
    return result.rows;
  } catch (error) {
    console.error('Error fetching user posts:', error);
    throw error;
  } finally {
    client.release();
  }
}
```

## Caching Strategies

```typescript
import Redis from 'ioredis';

class CacheManager {
  private redis: Redis;
  private defaultTTL: number;

  constructor(redisUrl: string, defaultTTL: number = 3600) {
    this.redis = new Redis(redisUrl);
    this.defaultTTL = defaultTTL;
  }

  async get<T>(key: string): Promise<T | null> {
    const data = await this.redis.get(key);
    return data ? JSON.parse(data) : null;
  }

  async set<T>(
    key: string,
    value: T,
    ttl: number = this.defaultTTL
  ): Promise<void> {
    await this.redis.set(
      key,
      JSON.stringify(value),
      'EX',
      ttl
    );
  }

  async invalidate(pattern: string): Promise<void> {
    const keys = await this.redis.keys(pattern);
    if (keys.length > 0) {
      await this.redis.del(...keys);
    }
  }
}

// Usage example
const cache = new CacheManager('redis://localhost:6379');

async function getCachedUserPosts(userId: string) {
  const cacheKey = `user:${userId}:posts`;
  
  // Try cache first
  const cached = await cache.get(cacheKey);
  if (cached) return cached;

  // If not in cache, get from database
  const posts = await getUserPosts(userId);
  
  // Store in cache
  await cache.set(cacheKey, posts);
  
  return posts;
}
```

## Data Partitioning

```sql
-- Create Partition Table
CREATE TABLE events (
    id UUID NOT NULL,
    user_id UUID NOT NULL,
    event_type VARCHAR(50) NOT NULL,
    event_data JSONB,
    created_at TIMESTAMP WITH TIME ZONE NOT NULL
) PARTITION BY RANGE (created_at);

-- Create Partitions
CREATE TABLE events_2024_q1 PARTITION OF events
    FOR VALUES FROM ('2024-01-01') TO ('2024-04-01');

CREATE TABLE events_2024_q2 PARTITION OF events
    FOR VALUES FROM ('2024-04-01') TO ('2024-07-01');

-- Add Indexes to Parent Table
CREATE INDEX idx_events_user_id ON events(user_id);
CREATE INDEX idx_events_event_type ON events(event_type);
CREATE INDEX idx_events_created_at ON events(created_at);
```

## Best Practices

1. Schema Design
   - Normalize appropriately
   - Use appropriate data types
   - Implement constraints
   - Plan for scaling

2. Performance
   - Index strategically
   - Optimize queries
   - Use connection pooling
   - Implement caching

3. Data Integrity
   - Use transactions
   - Implement constraints
   - Regular backups
   - Data validation

4. Security
   - Access control
   - Encryption at rest
   - Secure connections
   - Regular audits

## Conclusion

Good database design requires careful consideration of data structure, performance, and scalability. These patterns and practices help create robust and efficient database systems.
]]></content>
        <author>
            <name>Dibakar Mitra</name>
            <email>dibakarmitra07@gmail.com</email>
            <uri>https://www.dibakarmitra.com</uri>
        </author>
        <category label="Database" term="Database"/>
        <category label="SQL" term="SQL"/>
        <category label="NoSQL" term="NoSQL"/>
        <category label="Data Modeling" term="Data Modeling"/>
    </entry>
    <entry>
        <title type="html"><![CDATA[Frontend Performance Optimization: A Comprehensive Guide]]></title>
        <id>https://www.dibakarmitra.com/notes/frontend-performance-optimization</id>
        <link href="https://www.dibakarmitra.com/notes/frontend-performance-optimization"/>
        <updated>2023-12-28T00:00:00.000Z</updated>
        <summary type="html"><![CDATA[Learn advanced techniques for optimizing frontend performance in modern web applications]]></summary>
        <content type="html"><![CDATA[
# Frontend Performance Optimization: A Comprehensive Guide

Performance optimization is crucial for delivering excellent user experiences. This guide explores advanced techniques and best practices for optimizing frontend applications.

## Core Web Vitals

### Largest Contentful Paint (LCP)
```javascript
// Measure LCP
new PerformanceObserver((entryList) => {
  for (const entry of entryList.getEntries()) {
    console.log('LCP:', entry.startTime);
    console.log('Element:', entry.element);
  }
}).observe({ entryTypes: ['largest-contentful-paint'] });
```

### First Input Delay (FID)
```javascript
// Measure FID
new PerformanceObserver((entryList) => {
  for (const entry of entryList.getEntries()) {
    const delay = entry.processingStart - entry.startTime;
    console.log('FID:', delay);
  }
}).observe({ entryTypes: ['first-input'] });
```

## Image Optimization

### Next.js Image Component
```jsx
import Image from 'next/image';

function OptimizedImage() {
  return (
    <Image
      src="/large-image.jpg"
      alt="Optimized image"
      width={800}
      height={600}
      placeholder="blur"
      blurDataURL="data:image/jpeg;base64,..."
      priority={true}
    />
  );
}
```

### Lazy Loading Implementation
```javascript
// Intersection Observer for lazy loading
const lazyLoadImages = () => {
  const images = document.querySelectorAll('[data-src]');
  
  const imageObserver = new IntersectionObserver((entries) => {
    entries.forEach(entry => {
      if (entry.isIntersecting) {
        const img = entry.target;
        img.src = img.dataset.src;
        img.removeAttribute('data-src');
        imageObserver.unobserve(img);
      }
    });
  });

  images.forEach(img => imageObserver.observe(img));
};
```

## Code Splitting

### React.lazy and Suspense
```jsx
import React, { Suspense } from 'react';

const HeavyComponent = React.lazy(() => import('./HeavyComponent'));

function App() {
  return (
    <Suspense fallback={<LoadingSpinner />}>
      <HeavyComponent />
    </Suspense>
  );
}
```

### Route-Based Splitting
```javascript
// Next.js dynamic imports
import dynamic from 'next/dynamic';

const DynamicComponent = dynamic(() => import('../components/Heavy'), {
  loading: () => <p>Loading...</p>,
  ssr: false
});
```

## Bundle Optimization

### Webpack Configuration
```javascript
// webpack.config.js
module.exports = {
  optimization: {
    splitChunks: {
      chunks: 'all',
      maxInitialRequests: 25,
      minSize: 20000,
      cacheGroups: {
        vendor: {
          test: /[\\/]node_modules[\\/]/,
          name(module) {
            const packageName = module.context.match(
              /[\\/]node_modules[\\/](.*?)([\\/]|$)/
            )[1];
            return `vendor.${packageName.replace('@', '')}`;
          },
        },
      },
    },
  },
};
```

## State Management Optimization

### React Performance Hooks
```jsx
import { useMemo, useCallback } from 'react';

function ExpensiveComponent({ data, onUpdate }) {
  // Memoize expensive calculations
  const processedData = useMemo(() => {
    return data.map(item => expensiveOperation(item));
  }, [data]);

  // Memoize callbacks
  const handleClick = useCallback(() => {
    onUpdate(processedData);
  }, [processedData, onUpdate]);

  return (
    <div onClick={handleClick}>
      {processedData.map(item => (
        <Item key={item.id} {...item} />
      ))}
    </div>
  );
}
```

## CSS Performance

### Critical CSS
```javascript
// Extract critical CSS
const critical = require('critical');

critical.generate({
  base: 'dist/',
  src: 'index.html',
  target: {
    css: 'critical.css',
    html: 'index-critical.html',
  },
  width: 1300,
  height: 900,
});
```

### CSS-in-JS Optimization
```jsx
// Styled-components with dynamic props optimization
const StyledButton = styled.button`
  background: ${props => props.primary ? 'blue' : 'gray'};
  color: white;
  
  /* Use CSS variables for dynamic values */
  --button-padding: ${props => props.size === 'large' ? '1rem' : '0.5rem'};
  padding: var(--button-padding);
`;
```

## Memory Management

### Memory Leak Prevention
```javascript
class Component extends React.Component {
  componentDidMount() {
    this.interval = setInterval(this.tick, 1000);
    window.addEventListener('resize', this.handleResize);
  }

  componentWillUnmount() {
    // Clean up subscriptions and listeners
    clearInterval(this.interval);
    window.removeEventListener('resize', this.handleResize);
  }
}
```

## Network Optimization

### Service Worker Implementation
```javascript
// service-worker.js
const CACHE_NAME = 'v1';
const urlsToCache = [
  '/',
  '/styles/main.css',
  '/scripts/main.js'
];

self.addEventListener('install', event => {
  event.waitUntil(
    caches.open(CACHE_NAME)
      .then(cache => cache.addAll(urlsToCache))
  );
});

self.addEventListener('fetch', event => {
  event.respondWith(
    caches.match(event.request)
      .then(response => response || fetch(event.request))
  );
});
```

## Virtual DOM Optimization

### React Rendering Optimization
```jsx
// Use React.memo for component memoization
const MemoizedComponent = React.memo(function MyComponent(props) {
  return (
    <div>
      <ExpensiveTree {...props} />
    </div>
  );
}, (prevProps, nextProps) => {
  return prevProps.id === nextProps.id;
});
```

## Performance Monitoring

### Web Vitals Tracking
```javascript
import { getCLS, getFID, getLCP } from 'web-vitals';

function sendToAnalytics({ name, delta, id }) {
  // Send metrics to analytics
  gtag('event', name, {
    event_category: 'Web Vitals',
    event_label: id,
    value: Math.round(name === 'CLS' ? delta * 1000 : delta),
    non_interaction: true,
  });
}

getCLS(sendToAnalytics);
getFID(sendToAnalytics);
getLCP(sendToAnalytics);
```

## Best Practices

### 1. Loading Performance
- Implement progressive loading
- Use resource hints
- Optimize critical rendering path

### 2. Runtime Performance
- Avoid layout thrashing
- Use requestAnimationFrame
- Debounce and throttle events

### 3. Memory Management
- Clean up event listeners
- Use WeakMap for caching
- Monitor memory leaks

## Common Pitfalls

1. **Render Blocking Resources**
   - Unoptimized images
   - Render-blocking CSS/JS
   - Heavy third-party scripts

2. **State Management Issues**
   - Unnecessary re-renders
   - Deep component trees
   - Prop drilling

## Tools and Resources

1. **Performance Measurement**
   - Lighthouse
   - Chrome DevTools
   - WebPageTest

2. **Monitoring Tools**
   - Google Analytics
   - New Relic
   - Sentry

## Conclusion

Frontend 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.

## Resources

1. Web Vitals Documentation
2. Chrome DevTools Documentation
3. React Performance Documentation
4. MDN Performance Guide
5. Google PageSpeed Insights]]></content>
        <author>
            <name>Dibakar Mitra</name>
            <email>dibakarmitra07@gmail.com</email>
            <uri>https://www.dibakarmitra.com</uri>
        </author>
        <category label="Performance" term="Performance"/>
        <category label="Web Development" term="Web Development"/>
        <category label="JavaScript" term="JavaScript"/>
        <category label="React" term="React"/>
    </entry>
    <entry>
        <title type="html"><![CDATA[Cloud Native Architecture: Building Modern Scalable Systems]]></title>
        <id>https://www.dibakarmitra.com/notes/cloud-native-architecture</id>
        <link href="https://www.dibakarmitra.com/notes/cloud-native-architecture"/>
        <updated>2023-12-25T00:00:00.000Z</updated>
        <summary type="html"><![CDATA[A comprehensive guide to cloud native architecture principles, patterns, and best practices]]></summary>
        <content type="html"><![CDATA[
# Cloud Native Architecture: Building Modern Scalable Systems

Cloud 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.

## Core Principles of Cloud Native Architecture

### 1. Containerization
```yaml
# Example Dockerfile
FROM node:18-alpine
WORKDIR /app
COPY package*.json ./
RUN npm install
COPY . .
EXPOSE 3000
CMD ["npm", "start"]
```

### 2. Microservices
- Service independence
- Loose coupling
- API-first design
- Domain-driven design

### 3. DevOps Culture
- Continuous Integration
- Continuous Deployment
- Infrastructure as Code
- Automated testing

## Kubernetes: The Foundation

### Basic Deployment
```yaml
apiVersion: apps/v1
kind: Deployment
metadata:
  name: myapp
spec:
  replicas: 3
  selector:
    matchLabels:
      app: myapp
  template:
    metadata:
      labels:
        app: myapp
    spec:
      containers:
      - name: myapp
        image: myapp:1.0.0
        ports:
        - containerPort: 8080
```

### Service Definition
```yaml
apiVersion: v1
kind: Service
metadata:
  name: myapp-service
spec:
  selector:
    app: myapp
  ports:
  - port: 80
    targetPort: 8080
  type: LoadBalancer
```

## Infrastructure as Code (IaC)

### Terraform Example
```hcl
provider "aws" {
  region = "us-west-2"
}

resource "aws_eks_cluster" "main" {
  name     = "main-cluster"
  role_arn = aws_iam_role.eks_cluster.arn

  vpc_config {
    subnet_ids = var.subnet_ids
  }
}
```

## Service Mesh Architecture

### Istio Configuration
```yaml
apiVersion: networking.istio.io/v1alpha3
kind: VirtualService
metadata:
  name: myapp-route
spec:
  hosts:
  - myapp.example.com
  http:
  - route:
    - destination:
        host: myapp-service
        subset: v1
      weight: 90
    - destination:
        host: myapp-service
        subset: v2
      weight: 10
```

## Observability

### 1. Logging
```yaml
# Elasticsearch Fluentd Kibana (EFK) Stack
apiVersion: v1
kind: ConfigMap
metadata:
  name: fluentd-config
data:
  fluent.conf: |
    <source>
      @type tail
      path /var/log/containers/*.log
      pos_file /var/log/fluentd-containers.log.pos
      tag kubernetes.*
    </source>
```

### 2. Monitoring
```yaml
# Prometheus configuration
apiVersion: monitoring.coreos.com/v1
kind: ServiceMonitor
metadata:
  name: app-monitor
spec:
  selector:
    matchLabels:
      app: myapp
  endpoints:
  - port: metrics
```

### 3. Tracing
```javascript
// OpenTelemetry implementation
const tracer = opentelemetry.trace.getTracer('my-service');

async function handleRequest(req, res) {
  const span = tracer.startSpan('process-request');
  try {
    // Process request
    span.setStatus({ code: SpanStatusCode.OK });
  } catch (error) {
    span.setStatus({ code: SpanStatusCode.ERROR, message: error.message });
  } finally {
    span.end();
  }
}
```

## Scalability Patterns

### 1. Horizontal Pod Autoscaling
```yaml
apiVersion: autoscaling/v2
kind: HorizontalPodAutoscaler
metadata:
  name: myapp-hpa
spec:
  scaleTargetRef:
    apiVersion: apps/v1
    kind: Deployment
    name: myapp
  minReplicas: 2
  maxReplicas: 10
  metrics:
  - type: Resource
    resource:
      name: cpu
      target:
        type: Utilization
        averageUtilization: 80
```

### 2. Event-Driven Architecture
```javascript
// Event handler using CloudEvents
const cloudEvent = {
  specversion: "1.0",
  type: "com.example.order.created",
  source: "/orders",
  id: "123-456",
  data: {
    orderId: "12345",
    customer: "John Doe"
  }
};
```

## Security Best Practices

### 1. Pod Security Policies
```yaml
apiVersion: policy/v1beta1
kind: PodSecurityPolicy
metadata:
  name: restricted
spec:
  privileged: false
  seLinux:
    rule: RunAsAny
  runAsUser:
    rule: MustRunAsNonRoot
  fsGroup:
    rule: RunAsAny
```

### 2. Network Policies
```yaml
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: api-allow
spec:
  podSelector:
    matchLabels:
      app: api
  ingress:
  - from:
    - podSelector:
        matchLabels:
          role: frontend
```

## Disaster Recovery

### 1. Backup Strategy
```yaml
# Velero backup configuration
apiVersion: velero.io/v1
kind: Backup
metadata:
  name: daily-backup
spec:
  includedNamespaces:
  - production
  schedule: "0 1 * * *"
  ttl: 720h
```

### 2. Multi-Region Deployment
```hcl
# Terraform multi-region setup
module "eks_cluster_us_east" {
  source = "./modules/eks"
  region = "us-east-1"
}

module "eks_cluster_us_west" {
  source = "./modules/eks"
  region = "us-west-2"
}
```

## Cost Optimization

### 1. Resource Requests and Limits
```yaml
resources:
  requests:
    memory: "64Mi"
    cpu: "250m"
  limits:
    memory: "128Mi"
    cpu: "500m"
```

### 2. Spot Instances
```yaml
apiVersion: apps/v1
kind: Deployment
metadata:
  name: spot-deployment
spec:
  template:
    spec:
      nodeSelector:
        node.kubernetes.io/instance-type: spot
```

## Best Practices

1. **Infrastructure Management**
   - Use GitOps principles
   - Implement Infrastructure as Code
   - Regular security audits

2. **Application Design**
   - Follow twelve-factor app methodology
   - Implement circuit breakers
   - Use health checks

3. **Operations**
   - Implement automated rollbacks
   - Use blue-green deployments
   - Regular disaster recovery testing

## Common Challenges

1. **Complexity Management**
   - Service discovery
   - Configuration management
   - Dependency management

2. **Performance Optimization**
   - Resource utilization
   - Network latency
   - Cache optimization

## Future Trends

1. **FinOps Integration**
2. **Edge Computing**
3. **AI-Driven Operations**
4. **Zero Trust Security**

## Conclusion

Cloud 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.

## Resources

1. Cloud Native Computing Foundation
2. Kubernetes Documentation
3. Istio Service Mesh
4. Terraform Documentation
5. AWS EKS Best Practices]]></content>
        <author>
            <name>Dibakar Mitra</name>
            <email>dibakarmitra07@gmail.com</email>
            <uri>https://www.dibakarmitra.com</uri>
        </author>
        <category label="Cloud Native" term="Cloud Native"/>
        <category label="Kubernetes" term="Kubernetes"/>
        <category label="Microservices" term="Microservices"/>
        <category label="DevOps" term="DevOps"/>
    </entry>
    <entry>
        <title type="html"><![CDATA[AI and Machine Learning in Modern Web Development]]></title>
        <id>https://www.dibakarmitra.com/notes/ai-ml-web-development</id>
        <link href="https://www.dibakarmitra.com/notes/ai-ml-web-development"/>
        <updated>2023-12-20T00:00:00.000Z</updated>
        <summary type="html"><![CDATA[Exploring the integration of AI and ML technologies in web applications]]></summary>
        <content type="html"><![CDATA[
# AI and Machine Learning in Modern Web Development

Artificial 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.

## Client-Side Machine Learning with TensorFlow.js

### Basic Model Implementation
```javascript
import * as tf from '@tensorflow/tfjs';

// Create a simple neural network
const model = tf.sequential({
  layers: [
    tf.layers.dense({ inputShape: [4], units: 10, activation: 'relu' }),
    tf.layers.dense({ units: 3, activation: 'softmax' })
  ]
});

// Compile the model
model.compile({
  optimizer: 'adam',
  loss: 'categoricalCrossentropy',
  metrics: ['accuracy']
});
```

## Common AI/ML Use Cases in Web Development

### 1. Image Recognition
```javascript
// Using TensorFlow.js with a pre-trained MobileNet model
import * as tf from '@tensorflow/tfjs';
import * as mobilenet from '@tensorflow-models/mobilenet';

async function classifyImage(imageElement) {
  const model = await mobilenet.load();
  const predictions = await model.classify(imageElement);
  return predictions;
}
```

### 2. Natural Language Processing
```javascript
// Using Transformers.js for text processing
import { pipeline } from '@huggingface/transformers';

async function analyzeSentiment(text) {
  const sentiment = await pipeline('sentiment-analysis');
  const result = await sentiment(text);
  return result;
}
```

## AI-Powered Features

### 1. Smart Search Implementation
```typescript
interface SearchResult {
  content: string;
  relevanceScore: number;
}

async function semanticSearch(query: string): Promise<SearchResult[]> {
  const embedding = await getEmbedding(query);
  return searchWithEmbedding(embedding);
}
```

### 2. Recommendation Systems
```javascript
class RecommendationEngine {
  async getUserPreferences(userId) {
    // Fetch user interaction history
    const history = await getUserHistory(userId);
    
    // Generate recommendations using collaborative filtering
    return this.collaborativeFilter(history);
  }
}
```

## Performance Optimization

### 1. Model Optimization
```javascript
async function optimizeModel(model) {
  // Quantize the model to reduce size
  const quantizedModel = await tf.quantization.quantize(model);
  
  // Save the optimized model
  await quantizedModel.save('indexeddb://optimized-model');
}
```

### 2. Lazy Loading
```javascript
// Lazy load AI models
const loadModel = async () => {
  if (!globalModel) {
    globalModel = await tf.loadLayersModel('path/to/model.json');
  }
  return globalModel;
};
```

## Real-Time Processing

### WebGL Acceleration
```javascript
tf.setBackend('webgl').then(() => {
  console.log('Using WebGL backend');
});
```

## Best Practices

### 1. Model Management
- Version control for models
- Proper model caching
- Regular model updates

### 2. Error Handling
```javascript
async function safePredict(input) {
  try {
    const model = await loadModel();
    return await model.predict(input);
  } catch (error) {
    console.error('Prediction failed:', error);
    return fallbackPrediction(input);
  }
}
```

### 3. Privacy Considerations
- Local processing when possible
- Data minimization
- User consent management

## Integration Patterns

### 1. API-First Approach
```typescript
interface AIService {
  predict(input: any): Promise<Prediction>;
  train(data: TrainingData): Promise<void>;
  evaluate(testData: TestData): Promise<Metrics>;
}
```

### 2. Hybrid Processing
```javascript
class HybridMLSystem {
  async process(data) {
    // Try client-side processing first
    if (this.canProcessLocally(data)) {
      return await this.localProcess(data);
    }
    // Fall back to server
    return await this.serverProcess(data);
  }
}
```

## Common Challenges

1. **Model Size**
   - Implementation of progressive loading
   - Model compression techniques
   - Efficient caching strategies

2. **Processing Power**
   - Hardware acceleration
   - Batch processing
   - Optimization techniques

3. **Real-Time Requirements**
   - WebWorkers implementation
   - Stream processing
   - Performance monitoring

## Future Trends

1. **WebGPU Integration**
2. **Edge ML Processing**
3. **Federated Learning**

## Development Tools

### 1. Development Environment
```javascript
const devConfig = {
  enableDebugLogs: true,
  useTestModel: true,
  simulateLatency: false
};
```

### 2. Testing Framework
```javascript
describe('AI Model Tests', () => {
  it('should handle invalid inputs gracefully', async () => {
    const result = await model.predict(invalidInput);
    expect(result.isValid).toBe(false);
  });
});
```

## Conclusion

AI 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.

## Resources

1. TensorFlow.js Documentation
2. Hugging Face Transformers.js
3. WebGL Performance Guide
4. AI Model Optimization Techniques
5. Machine Learning Web Development Patterns]]></content>
        <author>
            <name>Dibakar Mitra</name>
            <email>dibakarmitra07@gmail.com</email>
            <uri>https://www.dibakarmitra.com</uri>
        </author>
        <category label="AI" term="AI"/>
        <category label="Machine Learning" term="Machine Learning"/>
        <category label="Web Development" term="Web Development"/>
        <category label="TensorFlow.js" term="TensorFlow.js"/>
    </entry>
    <entry>
        <title type="html"><![CDATA[Understanding Serverless Architecture: The Future of Cloud Computing]]></title>
        <id>https://www.dibakarmitra.com/notes/serverless-architecture</id>
        <link href="https://www.dibakarmitra.com/notes/serverless-architecture"/>
        <updated>2023-12-15T00:00:00.000Z</updated>
        <summary type="html"><![CDATA[A deep dive into serverless architecture, its benefits, and real-world applications]]></summary>
        <content type="html"><![CDATA[
# Understanding Serverless Architecture: The Future of Cloud Computing

Serverless 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.

## What is Serverless Architecture?

Serverless 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.

## Key Benefits

1. **Cost Efficiency**
   - Pay-per-execution pricing model
   - No idle server costs
   - Automatic scaling

2. **Reduced Operational Overhead**
   - No server management required
   - Automatic updates and security patches
   - Built-in high availability

3. **Improved Developer Productivity**
   - Focus on business logic
   - Faster time to market
   - Simplified deployment process

## Popular Serverless Platforms

### AWS Lambda
The pioneer in serverless computing, AWS Lambda supports multiple programming languages and seamlessly integrates with other AWS services.

### Azure Functions
Microsoft's serverless solution offers excellent .NET integration and competitive pricing.

### Google Cloud Functions
Provides seamless integration with Google's ecosystem and strong support for event-driven architectures.

## Best Practices

1. **Function Design**
   - Keep functions focused and small
   - Implement proper error handling
   - Use environment variables for configuration

2. **Performance Optimization**
   - Minimize cold starts
   - Optimize function dependencies
   - Implement caching where appropriate

## Real-World Applications

- API backends
- Data processing pipelines
- Scheduled tasks and cron jobs
- Real-time file processing
- IoT device data handling

## Challenges and Considerations

While serverless architecture offers numerous benefits, it's essential to consider potential challenges:

- Cold starts
- Limited execution duration
- Vendor lock-in
- Debugging complexity

## Conclusion

Serverless 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.

## References

1. AWS Lambda Documentation
2. Azure Functions Documentation
3. Cloud Native Computing Foundation
4. Serverless Framework Documentation]]></content>
        <author>
            <name>Dibakar Mitra</name>
            <email>dibakarmitra07@gmail.com</email>
            <uri>https://www.dibakarmitra.com</uri>
        </author>
        <category label="Cloud Computing" term="Cloud Computing"/>
        <category label="Serverless" term="Serverless"/>
        <category label="AWS Lambda" term="AWS Lambda"/>
        <category label="Azure Functions" term="Azure Functions"/>
    </entry>
    <entry>
        <title type="html"><![CDATA[Microservices Architecture: Best Practices and Design Patterns]]></title>
        <id>https://www.dibakarmitra.com/notes/microservices-best-practices</id>
        <link href="https://www.dibakarmitra.com/notes/microservices-best-practices"/>
        <updated>2023-12-10T00:00:00.000Z</updated>
        <summary type="html"><![CDATA[Essential best practices and patterns for building robust microservices architectures]]></summary>
        <content type="html"><![CDATA[
# Microservices Architecture: Best Practices and Design Patterns

Microservices 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.

## Core Principles of Microservices

### 1. Single Responsibility
Each microservice should focus on a single business capability and have a clear, well-defined purpose.

### 2. Independence
Services should be loosely coupled and independently deployable, allowing teams to work autonomously.

### 3. Data Ownership
Each service should own its data and internal logic, exposing functionality through well-defined APIs.

## Essential Best Practices

### 1. API Design
- Use REST or gRPC for service communication
- Implement versioning from day one
- Document APIs using OpenAPI/Swagger
- Design for backward compatibility

### 2. Data Management
- Implement database-per-service pattern
- Use event sourcing for data consistency
- Implement CQRS where appropriate
- Handle distributed transactions carefully

### 3. Service Discovery
- Implement service registry
- Use health checks
- Implement circuit breakers
- Enable dynamic scaling

### 4. Monitoring and Observability
- Implement distributed tracing
- Use correlation IDs
- Set up centralized logging
- Monitor key metrics

## Common Design Patterns

### 1. API Gateway Pattern
```text
Client → API Gateway → Microservices
```
Benefits:
- Single entry point
- Authentication/Authorization
- Request routing
- Response transformation

### 2. Event-Driven Architecture
- Publish-subscribe pattern
- Event sourcing
- CQRS (Command Query Responsibility Segregation)

### 3. Circuit Breaker Pattern
Prevents cascading failures across services:
- Closed (normal operation)
- Open (failure state)
- Half-open (testing recovery)

## Infrastructure Considerations

### 1. Containerization
- Use Docker for containerization
- Implement Kubernetes for orchestration
- Define resource limits
- Use multi-stage builds

### 2. CI/CD
- Automate deployment pipeline
- Implement blue-green deployments
- Use feature flags
- Automate testing

## Common Pitfalls to Avoid

1. **Premature Decomposition**
   - Don't start with too many services
   - Begin with a monolith if uncertain

2. **Inappropriate Service Boundaries**
   - Align with business domains
   - Consider data ownership

3. **Distributed Monolith**
   - Avoid tight coupling
   - Maintain service independence

## Security Best Practices

1. **Authentication/Authorization**
   - Implement OAuth 2.0/JWT
   - Use API keys
   - Implement rate limiting

2. **Network Security**
   - Use HTTPS everywhere
   - Implement network policies
   - Use service mesh for security

## Conclusion

Building 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.

## Further Reading

1. Building Microservices (Sam Newman)
2. Domain-Driven Design (Eric Evans)
3. Kubernetes Documentation
4. Spring Cloud Documentation]]></content>
        <author>
            <name>Dibakar Mitra</name>
            <email>dibakarmitra07@gmail.com</email>
            <uri>https://www.dibakarmitra.com</uri>
        </author>
        <category label="Microservices" term="Microservices"/>
        <category label="System Design" term="System Design"/>
        <category label="Architecture" term="Architecture"/>
        <category label="DevOps" term="DevOps"/>
    </entry>
    <entry>
        <title type="html"><![CDATA[Progressive Web Apps: The Future of Web Development]]></title>
        <id>https://www.dibakarmitra.com/notes/progressive-web-apps</id>
        <link href="https://www.dibakarmitra.com/notes/progressive-web-apps"/>
        <updated>2023-12-05T00:00:00.000Z</updated>
        <summary type="html"><![CDATA[A comprehensive guide to building modern Progressive Web Apps]]></summary>
        <content type="html"><![CDATA[
# Progressive Web Apps: The Future of Web Development

Progressive 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.

## What Makes an App a PWA?

### Core Features
1. **Progressive Enhancement**
   - Works for every user, regardless of browser
   - Basic content first, then enhanced features

2. **Responsive Design**
   - Adapts to any form factor
   - Mobile-first approach

3. **App-like Experience**
   - Fast loading
   - Smooth animations
   - Native-like interactions

## Essential PWA Components

### 1. Service Workers
Service workers are the backbone of PWAs, enabling:
- Offline functionality
- Background sync
- Push notifications

Example Service Worker Registration:
```javascript
if ('serviceWorker' in navigator) {
  window.addEventListener('load', () => {
    navigator.serviceWorker.register('/sw.js')
      .then(registration => {
        console.log('SW registered:', registration);
      })
      .catch(error => {
        console.log('SW registration failed:', error);
      });
  });
}
```

### 2. Web App Manifest
The manifest.json file defines how your app appears:
```json
{
  "name": "My PWA App",
  "short_name": "PWA",
  "start_url": "/",
  "display": "standalone",
  "background_color": "#ffffff",
  "theme_color": "#000000",
  "icons": [
    {
      "src": "/icon-192x192.png",
      "sizes": "192x192",
      "type": "image/png"
    }
  ]
}
```

## Performance Optimization

### 1. Caching Strategies
- Cache-first for static assets
- Network-first for dynamic content
- Stale-while-revalidate for balance

### 2. Loading Performance
- Implement lazy loading
- Use image optimization
- Minimize main thread work
- Implement code splitting

## Advanced PWA Features

### 1. Push Notifications
Engage users with timely updates:
- Request permission appropriately
- Send relevant notifications
- Handle notification clicks

### 2. Background Sync
Handle offline actions:
- Queue failed requests
- Retry when online
- Maintain data consistency

### 3. App Shell Architecture
Implement the app shell model:
- Instant loading
- Reliable performance
- Native-like navigation

## Testing and Debugging

### Tools
1. **Lighthouse**
   - Performance metrics
   - PWA checklist
   - Best practices

2. **Chrome DevTools**
   - Service worker debugging
   - Cache inspection
   - Network analysis

## Best Practices

### 1. Performance
- Implement PRPL pattern
- Use service worker strategies
- Optimize critical rendering path

### 2. User Experience
- Provide offline feedback
- Add to home screen prompt
- Smooth transitions

### 3. Security
- Serve over HTTPS
- Implement proper CSP
- Handle sensitive data carefully

## Common Challenges

1. **Browser Support**
   - Implement feature detection
   - Provide fallbacks
   - Progressive enhancement

2. **Cache Management**
   - Version control
   - Cache invalidation
   - Storage limits

## Future of PWAs

- Web Assembly integration
- Advanced APIs
- Better platform integration
- Improved app store presence

## Conclusion

PWAs 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.

## Resources

1. Google PWA Documentation
2. Mozilla Service Workers API
3. Web App Manifest Specification
4. Workbox Documentation]]></content>
        <author>
            <name>Dibakar Mitra</name>
            <email>dibakarmitra07@gmail.com</email>
            <uri>https://www.dibakarmitra.com</uri>
        </author>
        <category label="PWA" term="PWA"/>
        <category label="Web Development" term="Web Development"/>
        <category label="JavaScript" term="JavaScript"/>
        <category label="Performance" term="Performance"/>
    </entry>
    <entry>
        <title type="html"><![CDATA[Next.js 13: A Deep Dive into New Features]]></title>
        <id>https://www.dibakarmitra.com/notes/nextjs-13-features</id>
        <link href="https://www.dibakarmitra.com/notes/nextjs-13-features"/>
        <updated>2023-12-01T00:00:00.000Z</updated>
        <summary type="html"><![CDATA[Exploring the revolutionary features and improvements in Next.js 13]]></summary>
        <content type="html"><![CDATA[
# Next.js 13: A Deep Dive into New Features

Next.js 13 represents a significant leap forward in React-based web development, introducing groundbreaking features that enhance performance, developer experience, and application architecture.

## App Directory (Beta)

The new app directory introduces a more intuitive way to handle routing and layouts:

```typescript
// app/layout.tsx
export default function RootLayout({
  children,
}: {
  children: React.ReactNode
}) {
  return (
    <html lang="en">
      <body>{children}</body>
    </html>
  )
}
```

### Key Benefits
- Nested layouts
- Server components by default
- Simplified routing
- Improved performance

## Server Components

Server Components represent a paradigm shift in React development:

```typescript
// app/page.tsx
async function getData() {
  const res = await fetch('https://api.example.com/data')
  return res.json()
}

export default async function Page() {
  const data = await getData()
  return <main>{/* Use data */}</main>
}
```

### Advantages
- Reduced client-side JavaScript
- Improved initial page load
- Better SEO
- Simplified data fetching

## Data Fetching

### New Patterns
1. **Server-side Fetching**
```typescript
async function getData() {
  const res = await fetch('https://api.example.com/data', {
    next: { revalidate: 60 } // ISR
  })
  return res.json()
}
```

2. **Streaming with Suspense**
```typescript
import { Suspense } from 'react'

export default function Page() {
  return (
    <Suspense fallback={<Loading />}>
      <SlowComponent />
    </Suspense>
  )
}
```

## Turbopack (Alpha)

Next.js 13 introduces Turbopack, a Rust-based successor to Webpack:
- Up to 700x faster updates than Webpack
- Intelligent caching
- Optimized for Next.js

## Image Component Improvements

The new Image component is more powerful:

```typescript
import Image from 'next/image'

export default function Gallery() {
  return (
    <Image
      src="/photo.jpg"
      alt="Description"
      width={500}
      height={300}
      priority
    />
  )
}
```

### New Features
- Better performance
- Improved lazy loading
- Enhanced accessibility
- Native image optimization

## Font Optimization

Built-in font optimization:

```typescript
import { Inter } from 'next/font/google'

const inter = Inter({ subsets: ['latin'] })

export default function RootLayout({
  children,
}: {
  children: React.ReactNode
}) {
  return (
    <html lang="en" className={inter.className}>
      <body>{children}</body>
    </html>
  )
}
```

## Middleware Enhancements

More powerful middleware capabilities:

```typescript
// middleware.ts
import { NextResponse } from 'next/server'
import type { NextRequest } from 'next/server'

export function middleware(request: NextRequest) {
  const requestHeaders = new Headers(request.headers)
  requestHeaders.set('x-custom-header', 'custom-value')

  return NextResponse.next({
    request: {
      headers: requestHeaders,
    },
  })
}
```

## SEO Improvements

Enhanced metadata API:

```typescript
import { Metadata } from 'next'

export const metadata: Metadata = {
  title: 'My Page',
  description: 'Page description',
  openGraph: {
    title: 'My Page',
    description: 'Page description',
    images: ['/og-image.jpg'],
  },
}
```

## Performance Optimizations

1. **Automatic Code Splitting**
2. **Improved Static Generation**
3. **Enhanced Edge Runtime Support**

## Best Practices

### 1. Server Components Usage
- Use for data fetching
- Keep client components minimal
- Leverage streaming

### 2. Route Organization
- Group related routes
- Use loading.tsx for suspense
- Implement error boundaries

### 3. Performance
- Optimize images
- Use built-in font optimization
- Implement proper caching

## Migration Guide

1. **Update Dependencies**
2. **Move to App Directory**
3. **Adapt Data Fetching**
4. **Update Components**

## Conclusion

Next.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.

## Resources

1. Next.js Documentation
2. React Server Components RFC
3. Turbopack Documentation
4. Next.js GitHub Repository]]></content>
        <author>
            <name>Dibakar Mitra</name>
            <email>dibakarmitra07@gmail.com</email>
            <uri>https://www.dibakarmitra.com</uri>
        </author>
        <category label="Next.js" term="Next.js"/>
        <category label="React" term="React"/>
        <category label="Web Development" term="Web Development"/>
        <category label="JavaScript" term="JavaScript"/>
    </entry>
</feed>