Skip to content

maximseshuk/payload-storage-bunny

Repository files navigation

Bunny.net - Fast Global CDN

Bunny Storage Adapter for Payload CMS

GitHub Release Generic badge Generic badge NPM Downloads

Store and serve media files from your Payload CMS using Bunny's fast global CDN.

Built on top of @payloadcms/plugin-cloud-storage for seamless Payload CMS integration.

Table of Contents

Features

  • Bunny Storage - Upload files, images, and documents to Bunny's global CDN
  • Bunny Stream - Handle videos with HLS/MP4 streaming, adaptive bitrates, and thumbnails
  • TUS Resumable Uploads - Reliable uploads for large video files with auto-resume on interruption
  • Thumbnail Generation - Automatic thumbnails for admin panel and API responses with customizable transformations
  • Signed URLs - Secure file access with time limits and geo-restrictions
  • Custom URL Transformations - Apply query parameters or custom logic to file URLs
  • Access Control - Use Payload's access rules or direct CDN delivery
  • Automatic CDN Cache Purging - Invalidate cache on file upload/delete for instant updates
  • Per-Collection Configuration - Override global settings for specific collections

Tip

⚡ Performance: Set disablePayloadAccessControl: true for best performance. This lets users download files directly from Bunny's CDN servers instead of through your Payload server, making content delivery much faster.

Installation

Requires Payload CMS 3.53.0 or higher.

Important

Migration from v1.x: Version 2.0.0+ requires Payload CMS 3.53.0+. For older Payload versions (3.0.0 - 3.52.x), use version 1.x with the optional experimental replaceSaveButtonComponent feature to fix the field update bug. See Migration Guide for detailed upgrade instructions.

# npm
npm install @seshuk/payload-storage-bunny

# yarn
yarn add @seshuk/payload-storage-bunny

# pnpm
pnpm add @seshuk/payload-storage-bunny

Quick Start

1. Set up environment variables

Create a .env file in your project root:

BUNNY_STORAGE_API_KEY=your-storage-api-key
BUNNY_HOSTNAME=example.b-cdn.net
BUNNY_ZONE_NAME=your-storage-zone

2. Configure the plugin

Add the plugin to your Payload config:

import { buildConfig } from 'payload'
import { bunnyStorage } from '@seshuk/payload-storage-bunny'

export default buildConfig({
  plugins: [
    bunnyStorage({
      collections: {
        media: {
          prefix: 'media',
          disablePayloadAccessControl: true, // Use direct CDN access
        },
      },
      storage: {
        apiKey: process.env.BUNNY_STORAGE_API_KEY,
        hostname: process.env.BUNNY_HOSTNAME,
        zoneName: process.env.BUNNY_ZONE_NAME,
      },
    }),
  ],
})

3. Create your upload collection

Define a collection that uses the plugin:

import { CollectionConfig } from 'payload'

export const Media: CollectionConfig = {
  slug: 'media',
  upload: {
    disableLocalStorage: true, // Required - handled by Bunny.net
  },
  fields: [
    {
      name: 'alt',
      type: 'text',
    },
  ],
}

Configuration

Important

When you use this plugin, disableLocalStorage is automatically set to true for each collection. Files won't be stored on your server.

Warning

Service Requirement: You must configure at least one service - either storage (Bunny Storage) or stream (Bunny Stream). You can configure both for full functionality.

Note

Use enabled: false to disable the plugin entirely. When disabled, collections will fall back to Payload's default storage behavior.

Main plugin configuration options:

Option Type Required Description
enabled boolean Enable or disable the plugin (default: true)
apiKey string ⚠️ Bunny Account API key (required for purge feature)
collections object Which collections should use Bunny Storage
storage object ⚠️ Bunny Storage configuration (required if stream not provided)
stream object ⚠️ Bunny Stream configuration (required if storage not provided)
purge boolean | object CDN cache purging configuration (optional)
thumbnail boolean | object Global thumbnail settings (optional)
signedUrls boolean | object Global signed URLs configuration (optional)
urlTransform object Global URL transformation config (optional)
mediaPreview boolean | object Global media preview settings for all collections (optional)
i18n object Internationalization settings (optional)
experimental object Experimental features (optional)

Collections Configuration

Define which collections will use Bunny Storage:

Option Type Default Description
[collectionSlug] boolean | object - Enable Bunny Storage for collection (true) or with options
prefix string Collection slug Folder prefix within Bunny Storage
disablePayloadAccessControl boolean false Use direct CDN access (bypasses Payload auth)
purge boolean | object Global setting Override global cache purging config (false to disable)
storage false | object Global setting Disable storage for this collection (false) or override settings
storage.uploadTimeout number Global setting Override storage upload timeout in milliseconds
stream false | object Global setting Disable stream for this collection (false) or override settings
stream.mp4Fallback boolean Global setting Override MP4 fallback setting for videos
stream.thumbnailTime number Global setting Override default thumbnail time for videos (in milliseconds)
stream.tus.uploadTimeout number Global setting Override TUS upload timeout in seconds
stream.uploadTimeout number Global setting Override stream upload timeout in milliseconds
thumbnail boolean | object Global setting Override global thumbnail config
signedUrls boolean | object Global setting Override global signed URLs config
urlTransform object Global setting Override global URL transform config
mediaPreview boolean | object Global setting Override global media preview config (false to disable)

Examples:

Simple usage:

collections: {
  media: true, // Enable with defaults
  videos: {
    prefix: 'video-uploads',
    disablePayloadAccessControl: true
  },
  largeVideos: {
    prefix: 'large-videos',
    stream: {
      mp4Fallback: true,
      tus: {
        uploadTimeout: 7200 // 2 hours for large files
      }
    }
  }
}

Disable specific services per collection:

collections: {
  // Only use Bunny Storage (disable stream for this collection)
  images: {
    stream: false // Videos won't be uploaded to Bunny Stream
  },
  // Only use Bunny Stream (disable storage for this collection)
  videos: {
    storage: false // Only video files will be uploaded to Bunny Stream, others will fail
  },
}

Note

At least one service (storage or stream) must be enabled per collection. You cannot disable both.

The prefix option organizes files in folders within your Bunny Storage. For example, prefix: 'images' stores uploads in an "images" folder.

Storage Configuration

Connect to Bunny Storage:

Option Type Required Description
apiKey string Your Bunny Storage API key
hostname string Your CDN domain from Pull Zone (e.g., 'example.b-cdn.net')
zoneName string Your storage zone name
region string Storage region code ('uk', 'ny', 'la', 'sg', 'se', 'br', 'jh', 'syd')
tokenSecurityKey string Security key for signing storage URLs
uploadTimeout number Upload timeout in milliseconds (default: 120000)

Important

Bunny Storage requires a Pull Zone to be configured for your Storage Zone. Files will not be accessible without a properly configured Pull Zone. The hostname should be your Pull Zone hostname, not the Storage API endpoint. See Bunny's documentation on accessing and delivering files from Bunny Storage.

Stream Configuration

Optional settings for video handling:

Option Type Required Description
apiKey string Your Bunny Stream API key
hostname string Stream CDN domain (e.g., 'vz-abc123def-456.b-cdn.net')
libraryId number Your video library ID (e.g., 123456)
mimeTypes string[] File types that should use Bunny Stream (defaults to video/audio types)
mp4Fallback boolean Enable MP4 downloads (required with access control unless using signed URLs with redirect)
thumbnailTime number Default thumbnail time in milliseconds (specifies moment in video to capture)
tokenSecurityKey string Security key for signing stream URLs
uploadTimeout number Upload timeout in milliseconds (default: 300000)
tus boolean | object Enable TUS resumable uploads (see options below)
cleanup boolean | object Automatic cleanup of incomplete uploads (requires Jobs Queue setup, see options below)

Important

The stream.mimeTypes setting works together with your collection's mimeTypes setting. If a file type is allowed in stream config but blocked in your collection config, the collection setting takes priority and the file will be rejected.

TUS upload options:

Option Type Default Description
autoMode boolean true Auto-enable TUS for supported MIME types
checkAccess function Built-in check Custom authorization function
uploadTimeout number 3600 Upload timeout in seconds

Cleanup options:

Option Type Default Description
maxAge number 86400 Time in seconds after which incomplete uploads are considered dead
schedule object { cron: '0 2 * * *', queue: 'storage-bunny' } Cron schedule for cleanup task

Note

Cleanup feature requires Jobs Queue to be configured in your Payload setup. See Payload Jobs Queue documentation for setup instructions.

Warning

If you use Payload's access control without signed URLs, you must enable MP4 fallback both here and in your Bunny Stream settings. However, if you use signed URLs with staticHandler.useRedirect: true, MP4 fallback is not required as users are redirected directly to Bunny's HLS streams.

Note

Video support works even without Bunny Stream configured. If Bunny Stream is disabled, video files upload to Bunny Storage like any other file. Bunny Stream adds enhanced video features (streaming, adaptive bitrates, thumbnails).

Cache Purging Configuration

Enable automatic CDN cache purging for storage files (not applicable to Stream).

Configuration options:

  • purge: true - Enable with default settings
  • purge: false - Disable cache purging
  • purge: { ... } - Enable with custom settings (see options below)
Option Type Required Description
async boolean Wait for purge to complete (default: false)

Important

Cache purging requires a global apiKey to be configured at the plugin level. See Bunny API Key section for setup instructions.

When enabled, the plugin automatically purges CDN cache after:

  • File uploads
  • File deletions

This ensures visitors always see the most up-to-date files, especially important when replacing existing files (like during image cropping).

Examples:

// Simple enable with defaults
purge: true

// Disable
purge: false

// Custom configuration
purge: {
  async: true // Don't wait for purge to complete
}

Thumbnail Configuration

Enable thumbnail generation for upload collections. When enabled, the plugin provides a function to Payload's adminThumbnail configuration that generates thumbnail URLs for your files.

For Bunny Stream videos: Uses the thumbnail generated at stream.thumbnailTime moment.

For images: Uses the original file or a specific size if sizeName is configured.

Use thumbnail: true to enable with defaults, thumbnail: false to disable, or provide an object to customize:

Note

This configures Payload's upload.adminThumbnail function which populates the thumbnailURL field in API responses.

Option Type Default Description
appendTimestamp boolean false Add timestamp to bust cache
streamAnimated boolean false Use animated preview (WebP) instead of static thumbnail for Bunny Stream videos
queryParams object {} Custom query parameters appended to URLs (optimized for Bunny Optimizer)
sizeName string - Use specific size from upload collection's sizes instead of original file

Examples:

// Enable animated preview for Bunny Stream videos
thumbnail: {
  streamAnimated: true,
  appendTimestamp: true
}

// Custom query parameters for image optimization
thumbnail: {
  queryParams: {
    width: '300',
    height: '300',
    quality: '90'
  }
}

// Use specific size from upload collection sizes
thumbnail: {
  sizeName: 'thumbnail', // Uses 'thumbnail' size from collection's sizes config
  appendTimestamp: true  // Can be combined with other options
}

When appendTimestamp is enabled, the plugin automatically adds a timestamp parameter to image URLs in the admin panel and API responses. This ensures updated files show the latest version without browser caching issues. Additionally, when appendTimestamp is enabled, Payload's cache tags are automatically disabled for thumbnails to prevent caching conflicts.

The streamAnimated option enables animated WebP previews for Bunny Stream videos instead of static JPEG thumbnails. This option only works when stream configuration is enabled for the collection. When enabled, the plugin uses preview.webp URLs instead of thumbnail.jpg for video thumbnails.

The queryParams option adds custom query parameters to URLs. It works great with Bunny's Image Optimizer service for resizing, cropping, and optimizing images on-the-fly, but you can add any query parameters you need.

The sizeName option allows you to use a specific size variant from your upload collection's sizes configuration instead of the original file for admin thumbnails. This works only with image uploads that have sizes configured in your Payload collection. If the specified size doesn't exist in the document, it falls back to the original file.

Signed URLs Configuration

Enable signed URLs for secure file access:

Option Type Default Description
expiresIn number 7200 Link expiration time in seconds
allowedCountries string[] [] Allowed countries (ISO 3166-1 alpha-2 codes)
blockedCountries string[] [] Blocked countries (ISO 3166-1 alpha-2 codes)
shouldUseSignedUrl function Always sign Custom function to determine when to use signed URLs
staticHandler object {} Static handler behavior (see below)

Static handler options:

When Payload access control is enabled, files can be served in two ways:

  1. Proxying (default): Payload downloads the file from Bunny and serves it to the user
  2. Redirect: Payload generates a signed URL and redirects the user to download directly from Bunny

Tip

Redirect is recommended as it reduces server load and improves performance by avoiding file proxying.

Option Type Default Description
useRedirect boolean false Redirect instead of proxying content (recommended for better performance)
redirectStatus number 302 HTTP status code for redirects (301, 302, 307, 308)
expiresIn number Uses main expiresIn Override expiration time for redirects

Note

Signed URLs work with both Storage and Stream when tokenSecurityKey is configured.

URL Transform Configuration

Custom URL transformations for complete control over file URLs.

Simple transform options:

Option Type Default Description
appendTimestamp boolean false Add timestamp parameter to URLs
queryParams object {} Static query parameters appended to URLs

Advanced transform function:

Option Type Description
transformUrl function Custom function for complete URL control

Function signature:

;(args: {
  baseUrl: string
  collection: CollectionConfig
  data?: Record<string, unknown>
  filename: string
  prefix?: string
}) => string

Warning

URL transforms don't work when disablePayloadAccessControl is true for the collection.

TUS Uploads Configuration

TUS (resumable uploads) enables reliable uploads of large video files by breaking them into chunks and allowing resume if the connection is interrupted.

Why use TUS uploads:

  • Large files: Essential for video files over 100MB
  • Unreliable connections: Automatically resumes interrupted uploads
  • Serverless environments: Perfect for platforms like Vercel with request timeout and file size limits
  • Better UX: Users don't lose progress if something goes wrong

Upload modes:

  • Auto mode (autoMode: true): TUS is automatically enabled for supported video/audio files
  • Manual mode (autoMode: false): Admin UI shows a toggle button to switch between standard and TUS uploads

Configuration:

  • Simple enable: tus: true (uses auto mode by default)
  • Detailed configuration: See Stream Configuration section for all TUS options

Media Preview

Add preview capability in admin panels to view media files directly in the UI. Works in both table cells and document views. Supports images, videos, audio, and documents.

Examples:

Global configuration (all collections):

bunnyStorage({
  mediaPreview: true, // Enable with defaults for all collections
  // OR with custom settings
  mediaPreview: {
    mode: 'fullscreen',
    contentMode: {
      video: 'inline',
      audio: 'inline',
    },
  },
  collections: {
    media: true,
    videos: true,
  },
  // ... storage/stream config
})

Per-collection configuration:

bunnyStorage({
  collections: {
    media: {
      mediaPreview: true, // Enable with defaults
    },
    videos: {
      mediaPreview: {
        mode: 'fullscreen',
        contentMode: {
          video: 'inline',
          audio: 'inline',
          image: 'newTab',
          document: 'newTab',
        },
        position: { after: 'filename' },
      },
    },
    documents: {
      mediaPreview: false, // Disable for this collection
    },
  },
  // ... storage/stream config
})

Manual field addition:

import { mediaPreviewField } from '@seshuk/payload-storage-bunny'

export const Media: CollectionConfig = {
  slug: 'media',
  upload: true,
  fields: [
    mediaPreviewField({
      mode: 'fullscreen',
      contentMode: {
        video: 'inline',
        image: 'newTab',
      },
    }),
  ],
}

Configuration options:

Option Type Default Description
mode string auto auto (smart) or fullscreen (always modal)
contentMode object - Configure how each file type opens
contentMode.video string inline inline (popup/modal) or newTab (new browser tab)
contentMode.audio string inline inline (popup/modal) or newTab (new browser tab)
contentMode.image string inline inline (popup/modal) or newTab (new browser tab)
contentMode.document string inline inline (popup/modal) or newTab (new browser tab)
position string/object last Where to insert field (see position options below)
overrides object - Override field properties

Mode options:

  • auto - Table cells show popup, field shows fullscreen modal, mobile always uses fullscreen
  • fullscreen - Always shows fullscreen modal everywhere

Position options:

  • 'first' - Insert at the beginning of fields array
  • 'last' - Insert at the end of fields array (default)
  • { after: 'fieldName' } - Insert after specific field (e.g., { after: 'alt' })
  • { before: 'fieldName' } - Insert before specific field (e.g., { before: 'alt' })
  • Supports dot notation for nested fields (e.g., { after: 'meta.title' })

Supported file formats:

  • Videos - All video formats (MP4, WebM, MOV, AVI, etc.) - Uses Bunny Stream player if configured, otherwise native HTML5
  • Audio - All audio formats (MP3, WAV, OGG, FLAC, etc.) - Uses Bunny Stream player if configured, otherwise native HTML5
  • Images - All image formats (JPEG, PNG, GIF, WebP, SVG, etc.)
  • Documents - PDF, Office files (Word, Excel, PowerPoint), text files (TXT, HTML, CSS, JS, PHP, C, C++), Adobe files (AI, PSD), CAD files (DXF), Pages, PostScript, XPS, and more (max 25MB)

Access Control Configuration

Example:

collections: {
  media: {
    prefix: 'media',
    disablePayloadAccessControl: true
  }
}

When disablePayloadAccessControl is false (default):

  • Files go through Payload's API
  • Your access rules work
  • Videos need MP4 fallback enabled OR signed URLs with redirect
  • MP4s are served instead of HLS (unless using signed URLs with redirect)
  • Good for files that need protection

Tip

Use signed URLs with redirect to serve HLS streams directly and reduce server load

When disablePayloadAccessControl: true:

  • Files go directly from Bunny CDN
  • No access rules
  • Videos use HLS streams (playlist.m3u8)
  • Faster delivery but open access
  • No need for MP4 fallback

CDN Cache Management

There are two approaches to managing CDN cache for your Bunny Storage files:

Option 1: Automatic Cache Purging

Enable automatic cache purging when files are uploaded or deleted:

Example:

// At plugin level
apiKey: process.env.BUNNY_API_KEY, // Required for purge
purge: true, // Simple enable with defaults

// OR with custom settings
purge: {
  async: false // Wait for purge to complete (default: false)
}

This is the most comprehensive approach as it ensures CDN cache is immediately purged when files change, making updated content available to all visitors.

Per-collection override:

collections: {
  images: {
    purge: false // Disable cache purging for this collection
  },
  documents: {
    purge: {
      async: true // Override async setting for this collection
    }
  },
  videos: true // Uses global purge config
}

Option 2: Timestamp-Based Cache Busting

Append timestamps to file URLs to force browser cache updates without purging CDN cache.

Configuration:

For thumbnail URLs (thumbnailURL field):

thumbnail: {
  appendTimestamp: true
}

For all file URLs (url field):

urlTransform: {
  appendTimestamp: true
}

Bunny CDN configuration:

To make this work, configure your Pull Zone:

  1. Go to your Pull Zone settings
  2. Navigate to the "Caching" section
  3. Enable "Vary Cache" for "URL Query String"
  4. Add "t" to the "Query String Vary Parameters" list

How it works:

This approach appends a timestamp parameter (?t=1234567890) to file URLs. When a file is updated, the timestamp changes, causing browsers and Bunny CDN to treat it as a new file and fetch the latest version.

Comparison:

  • Automatic cache purging - Immediate updates everywhere, requires global apiKey
  • Timestamp-based cache busting - Simpler setup, works without apiKey, updates only when files are re-uploaded

Getting API Keys

Tip

New to Bunny.net? Sign up here to get started with fast global CDN and streaming services.

Bunny Storage API Key

To get your Bunny Storage API key:

  1. Go to your Bunny Storage dashboard
  2. Click on your Storage Zone
  3. Navigate to FTP & API Access section
  4. Copy the Password field as your API key

    [!IMPORTANT] Use the full Password, not the Read-only password (it won't work for uploads)

  5. Note your Username (this is your zoneName parameter)
  6. Note the Hostname value to determine your region (e.g., ny.storage.bunnycdn.com = region ny)

Note

The hostname parameter in plugin configuration comes from your Pull Zone, not from this section.

Bunny Stream API Key

To get your Bunny Stream API key:

  1. Go to your Bunny Stream dashboard
  2. Select your Video Library
  3. Click on API in the sidebar
  4. Copy the Video Library ID (use for libraryId setting, e.g., "123456")
  5. Copy the CDN Hostname (use for hostname setting, e.g., "vz-abc123def-456.b-cdn.net")
  6. Copy the API Key (found at the bottom of the page)

Bunny API Key

To get your Bunny API key:

  1. Go to your Bunny.net dashboard
  2. Click on your account in the top-right corner
  3. Select Account settings from the dropdown menu
  4. Click on API in the sidebar menu
  5. Copy the API key displayed on the page

Token Security Keys

Token security keys are used for signed URLs to provide secure access to files.

Storage Token Security Key

To get your Storage token security key:

  1. Go to your Bunny.net dashboard
  2. Navigate to DeliveryCDN
  3. Select your Pull Zone
  4. Click on Security in the sidebar
  5. Click on Token Authentication
  6. Enable Token authentication
  7. Copy the URL token authentication Key

Stream Token Security Key

To get your Stream token security key:

  1. Go to your Bunny.net dashboard
  2. Navigate to DeliveryStream
  3. Select your Video Library
  4. Click on API in the sidebar
  5. Find CDN zone management section
  6. Click Manage button
  7. Click on Security in the sidebar
  8. Click on Token Authentication
  9. Enable Token authentication
  10. Copy the URL token authentication Key

Storage Regions

Choose where to store your files. If you don't pick a region, the default storage location is used.

Use only the region code in the region setting:

  • Default: leave empty
  • uk - London, UK
  • ny - New York, US
  • la - Los Angeles, US
  • sg - Singapore
  • se - Stockholm, SE
  • br - São Paulo, BR
  • jh - Johannesburg, SA
  • syd - Sydney, AU

To determine your region, check your Bunny Storage Zone settings. Pick a region closest to your users for best performance. The region code is found in your Storage Zone's hostname (e.g., if your endpoint is ny.storage.bunnycdn.com, use ny as the region).

Example:

storage: {
  apiKey: process.env.BUNNY_STORAGE_API_KEY,
  hostname: 'example.b-cdn.net',
  region: 'ny',  // Just 'ny', not 'ny.storage.bunnycdn.com'
  zoneName: 'my-zone'
}

Basic Usage Example

Storage + Stream (Full Configuration)

import { buildConfig } from 'payload'
import { bunnyStorage } from '@seshuk/payload-storage-bunny'

export default buildConfig({
  plugins: [
    bunnyStorage({
      // Bunny Account API key for account-level operations
      apiKey: process.env.BUNNY_API_KEY,
      collections: {
        media: {
          prefix: 'media',
          disablePayloadAccessControl: true,
        },
      },
      storage: {
        apiKey: process.env.BUNNY_STORAGE_API_KEY,
        hostname: 'example.b-cdn.net',
        zoneName: 'your-storage-zone',
      },
      stream: {
        apiKey: process.env.BUNNY_STREAM_API_KEY,
        hostname: 'vz-abc123def-456.b-cdn.net',
        libraryId: 123456,
        tus: true, // Enable resumable uploads
      },
      // Optional: Auto-purge CDN cache (requires apiKey)
      purge: true,
    }),
  ],
})

Storage Only (Files + Basic Videos)

export default buildConfig({
  plugins: [
    bunnyStorage({
      collections: {
        media: { prefix: 'uploads', disablePayloadAccessControl: true },
      },
      storage: {
        apiKey: process.env.BUNNY_STORAGE_API_KEY,
        hostname: 'example.b-cdn.net',
        zoneName: 'your-storage-zone',
      },
    }),
  ],
})

Stream Only (Advanced Video Features)

export default buildConfig({
  plugins: [
    bunnyStorage({
      collections: {
        videos: { prefix: 'videos' },
      },
      stream: {
        apiKey: process.env.BUNNY_STREAM_API_KEY,
        hostname: 'vz-abc123def-456.b-cdn.net',
        libraryId: 123456,
        mp4Fallback: true,
        tus: true,
      },
    }),
  ],
})

For detailed configuration examples and advanced use cases, see docs/examples.md.


License

This project is licensed under the MIT License - see the LICENSE file for details.

Support

Need help? Here are some resources:

Credits

Built with ❤️ for the Payload CMS community.


Disclosure: Links to bunny.net in this documentation are referral links.