Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Sidecar Browsershot Laravel Package

wnx/sidecar-browsershot

Run Spatie Browsershot on AWS Lambda via Sidecar in Laravel—no need to install Node, Puppeteer, or Chrome on your servers. Deploy a Lambda function and generate PDFs/screenshots with headless Chrome handled remotely.

View on GitHub
Deep Wiki
Context7
## Getting Started

### Minimal Setup
1. **Prerequisites**: Ensure `spatie/browsershot` and `hammerstone/sidecar` are installed (skip Chrome/Puppeteer installation).
2. **Install Package**:
   ```bash
   composer require wnx/sidecar-browsershot
  1. Publish Config:
    php artisan vendor:publish --tag="sidecar-browsershot-config"
    
  2. Register Lambda Function: Add \Wnx\SidecarBrowsershot\Functions\BrowsershotFunction::class to sidecar.php under 'functions'.
  3. Deploy:
    php artisan sidecar:deploy --activate
    

First Use Case

Replace Browsershot with BrowsershotLambda for Lambda-based rendering:

use Wnx\SidecarBrowsershot\BrowsershotLambda;

// Generate PDF from URL
BrowsershotLambda::url('https://example.com')->save('example.pdf');

// Generate image from HTML
BrowsershotLambda::html('<h1>Hello</h1>')->save('image.png');

Implementation Patterns

Core Workflow

  1. Invoke Lambda:

    BrowsershotLambda::url('https://example.com')->save('output.pdf');
    
    • Under the hood, Sidecar serializes the request, invokes the Lambda function, and returns the result.
  2. S3 Integration:

    • Read from S3 (for large HTML files):
      BrowsershotLambda::readHtmlFromS3('s3/path/to/file.html')->save('output.pdf');
      
    • Save to S3 (avoid Lambda response size limits):
      BrowsershotLambda::url('https://example.com')->saveToS3('s3/path/output.pdf');
      
  3. Image Manipulation (requires spatie/image):

    BrowsershotLambda::url('https://example.com')
        ->windowSize(1920, 1080)
        ->fit(\Spatie\Image\Enums\Fit::Contain, 200, 200)
        ->save('resized.png');
    

Advanced Patterns

  • Warming Instances: Enable faster execution by pre-warming Lambda instances:

    // In .env
    SIDECAR_BROWSERSHOT_WARMING_INSTANCES=3
    

    Or via config: sidecar-browsershot.php > 'warming' => 3.

  • Custom Fonts: Place fonts in resources/sidecar-browsershot/fonts/ (configurable via sidecar-browsershot.fonts). The package auto-includes them in the Lambda deployment.

  • Error Handling: Wrap calls in try-catch to handle Lambda timeouts or failures:

    try {
        BrowsershotLambda::url('https://example.com')->save('output.pdf');
    } catch (\Exception $e) {
        Log::error('BrowsershotLambda failed: ' . $e->getMessage());
        // Fallback logic (e.g., retry or use local Browsershot)
    }
    
  • Queue Jobs: Offload heavy rendering to queues (e.g., Laravel Queues) to avoid timeouts:

    RenderPdfJob::dispatch('https://example.com', 'output.pdf');
    

Gotchas and Tips

Pitfalls

  1. Lambda Timeouts:

    • Default Lambda timeout is 3 seconds (adjustable via Sidecar config).
    • Fix: Increase timeout in sidecar.php or use ->timeout(30) on the chain.
    • Workaround: Break large tasks into smaller chunks or use queues.
  2. S3 Permissions:

    • Ensure the Lambda execution role has s3:GetObject (for reading) and s3:PutObject (for writing) permissions.
    • Error: AWS Access Denied when using readHtmlFromS3 or saveToS3.
    • Fix: Attach the correct IAM policy to the Sidecar execution role.
  3. Image Manipulation on S3:

    • fit() or other image manipulations download the file locally, process it, and re-upload.
    • Performance Impact: Avoid for large files (>5MB). Use local processing instead.
  4. Cold Starts:

    • Lambda cold starts add ~1-2 seconds latency.
    • Mitigation: Use warming (SIDECAR_BROWSERSHOT_WARMING_INSTANCES) or provisioned concurrency.
  5. Deprecated Methods:

    • chromium.font() was removed in v3.0.0. Use the resources/sidecar-browsershot/fonts/ folder instead.
  6. Layer Updates:

    • The package uses a pre-built Lambda layer (sidecar-browsershot-layer).
    • Manual Update: Redeploy Lambda after upgrading the package to ensure you get the latest Chromium/Puppeteer versions.

Debugging Tips

  1. Lambda Logs:

    • Check CloudWatch logs for the BrowsershotFunction to debug failures.
    • Enable Sidecar debug mode:
      'debug' => env('APP_DEBUG', false),
      
      in sidecar.php.
  2. Local Testing:

    • Use sidecar:local to test Lambda functions locally:
      php artisan sidecar:local
      
    • Mock the Lambda response for unit tests:
      $this->mock(BrowsershotLambda::class)->shouldReceive('url')
          ->andReturnSelf()
          ->shouldReceive('save')
          ->andReturn(true);
      
  3. Payload Size Limits:

    • Lambda payloads are limited to 6MB (request) and 6MB (response).
    • Workaround: Use saveToS3 for large outputs or split files.
  4. Environment Variables:

    • Ensure .env includes:
      SIDECAR_BROWSERSHOT_WARMING_INSTANCES=1
      AWS_REGION=us-east-1
      

Extension Points

  1. Custom Lambda Layers:

    • Override the Chromium layer in sidecar-browsershot.php:
      'layers' => [
          'arn:aws:lambda:us-east-1:123456789012:layer:custom-chrome-layer:1',
      ],
      
  2. Pre/Post-Processing:

    • Extend BrowsershotLambda by creating a decorator:
      class CustomBrowsershot extends BrowsershotLambda {
          public function addWatermark(string $text) {
              $this->html = $this->html . "<div style='position: absolute; bottom: 10px;'>$text</div>";
              return $this;
          }
      }
      
  3. Event Listeners:

    • Trigger actions after PDF/image generation:
      BrowsershotLambda::url('https://example.com')
          ->save('output.pdf')
          ->then(function () {
              event(new PdfGenerated('output.pdf'));
          });
      
  4. Fallback Mechanism:

    • Implement a fallback to local Browsershot if Lambda fails:
      try {
          BrowsershotLambda::url($url)->save($path);
      } catch (\Exception $e) {
          \Spatie\Browsershot\Browsershot::url($url)->save($path);
      }
      

Configuration Quirks

  1. Font Path:

    • Default font path: resources/sidecar-browsershot/fonts/.
    • Customize via sidecar-browsershot.php:
      'fonts' => 'custom/path/to/fonts',
      
  2. Timeout Handling:

    • Lambda timeout is set in sidecar.php:
      'timeout' => 15, // seconds
      
    • Override per request:
      BrowsershotLambda::url('https://example.com')->timeout(30)->save('output.pdf');
      
  3. Node.js Runtime:

    • The package uses Node.js 24 (as of v3.1.0). Ensure your Lambda runtime matches.
    • Error: Runtime.ImportModuleError if Node versions mismatch.
  4. Browsershot Version:

    • The package drops support for Browsershot v4 (v2.8.0+). Ensure compatibility:
      composer require spatie/browsershot:^5.0
      

---
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
codraw/entity-migrator
codraw/doctrine-extra
codraw/aws-tool-kit
codraw/validator
codraw/workflow
codraw/open-api
codraw/cron-job
codraw/process
codraw/log
nexmo/api-specification
capell-app/block-library
axium/identity
cetria/laravel-dummy-models
cetria/reflection-helper
agropredict/sso-auth-bundle
evolvestudio/spam-protection
datacore/hub-sdk
develia/commons
cuci/prototurk-sdk
cuci/prototurk-sdk-symfony