Skip to content

Latest commit

 

History

History
454 lines (325 loc) · 10.7 KB

File metadata and controls

454 lines (325 loc) · 10.7 KB

📖 Setup Guide - Video Streaming Integration

This comprehensive guide will walk you through setting up and deploying your video streaming platform with Cloudflare Stream.

Table of Contents

  1. Prerequisites
  2. Cloudflare Stream Setup
  3. Project Configuration
  4. Video Upload
  5. Local Development
  6. Deployment
  7. Troubleshooting

Prerequisites

Before you begin, ensure you have:

  • ✅ A modern web browser (Chrome, Firefox, Safari, or Edge)
  • ✅ A code editor (VS Code, Sublime Text, etc.)
  • ✅ Basic knowledge of HTML, CSS, and JavaScript
  • ✅ A Cloudflare account (free tier available)
  • ✅ (Optional) A local web server for development

Cloudflare Stream Setup

Step 1: Create a Cloudflare Account

  1. Go to https://dash.cloudflare.com/sign-up
  2. Sign up for a free account
  3. Verify your email address

Step 2: Enable Cloudflare Stream

  1. Log in to your Cloudflare dashboard
  2. Navigate to Stream from the left sidebar
  3. Click "Enable Stream" if not already enabled
  4. Note: Cloudflare Stream pricing starts at $1 per 1,000 minutes of video stored and $1 per 1,000 minutes delivered

Step 3: Get Your Account ID

  1. In the Cloudflare dashboard, go to Stream
  2. Your Account ID is displayed in the URL bar or on the Stream page
  3. Copy this ID - you'll need it for configuration

Step 4: Create an API Token

  1. Click on your profile icon (top right) → My Profile
  2. Select API Tokens from the left menu
  3. Click "Create Token"
  4. Choose "Create Custom Token"
  5. Configure the token:
    • Token name: Video Streaming Integration
    • Permissions:
      • Account → Stream → Read
      • (Optional) Account → Stream → Edit (if you want to upload via API)
    • Account Resources: Include → Your Account
  6. Click "Continue to summary" → "Create Token"
  7. IMPORTANT: Copy your token immediately! You won't be able to see it again

Project Configuration

Step 1: Clone or Download the Project

# Clone the repository (if using git)
git clone <your-repo-url>
cd Video-Streaming-Integration

# Or simply download and extract the ZIP file

Step 2: Configure API Credentials

  1. Navigate to the js folder in the project
  2. Copy config.example.js to config.js:
    cp js/config.example.js js/config.js
  3. Open js/config.js in your code editor
  4. Replace the placeholder values:
    const CONFIG = {
        ACCOUNT_ID: 'your-actual-account-id-here',
        API_TOKEN: 'your-actual-api-token-here',
        // ... rest of config
    };

Step 3: Update .gitignore

The config.js file is already in .gitignore to prevent accidentally committing your credentials. Never commit this file to version control!


Video Upload

Method 1: Upload via Cloudflare Dashboard (Easiest)

  1. Go to your Cloudflare dashboard → Stream
  2. Click "Upload" button
  3. Select your video file(s)
  4. Wait for upload and processing to complete
  5. Once processed, click on the video to get its Video ID
  6. Copy the Video ID for use in your config

Method 2: Upload via API (Advanced)

// Example using fetch API
async function uploadVideo(file) {
    const formData = new FormData();
    formData.append('file', file);
    
    const response = await fetch(
        `https://api.cloudflare.com/client/v4/accounts/${ACCOUNT_ID}/stream`,
        {
            method: 'POST',
            headers: {
                'Authorization': `Bearer ${API_TOKEN}`
            },
            body: formData
        }
    );
    
    const data = await response.json();
    console.log('Video ID:', data.result.uid);
}

Method 3: Upload via TUS Protocol

For large files, use TUS resumable uploads:

// Using tus-js-client
const upload = new tus.Upload(file, {
    endpoint: `https://api.cloudflare.com/client/v4/accounts/${ACCOUNT_ID}/stream`,
    headers: {
        'Authorization': `Bearer ${API_TOKEN}`
    },
    chunkSize: 52428800, // 50 MB
    onError: function(error) {
        console.error('Upload failed:', error);
    },
    onSuccess: function() {
        console.log('Upload complete!');
    }
});

upload.start();

Updating Video IDs in Config

After uploading videos, update your config.js:

DEMO_VIDEOS: [
    {
        id: 'actual-video-id-1',
        title: 'Your Video Title',
        description: 'Your video description',
        thumbnail: 'https://customer-...'
    },
    // Add more videos...
]

Local Development

Option 1: Simple HTTP Server (Python)

# Python 3
python -m http.server 8000

# Python 2
python -m SimpleHTTPServer 8000

Then open: http://localhost:8000

Option 2: Using Node.js

# Install http-server globally
npm install -g http-server

# Run server
http-server -p 8000

# Or use live-server for auto-reload
npm install -g live-server
live-server

Option 3: VS Code Live Server Extension

  1. Install "Live Server" extension in VS Code
  2. Right-click on index.html
  3. Select "Open with Live Server"

Testing Your Setup

  1. Open index.html in your browser
  2. Navigate to the video player page
  3. Check browser console for any errors
  4. Verify videos load in the playlist
  5. Test play/pause, seeking, and other controls

Deployment

Option 1: Cloudflare Pages (Recommended)

  1. Push your code to GitHub
  2. Go to Cloudflare dashboard → Pages
  3. Click "Create a project"
  4. Connect your GitHub repository
  5. Configure build settings:
    • Build command: (leave empty)
    • Build output directory: /
  6. Add environment variables (if needed)
  7. Click "Save and Deploy"

Your site will be deployed to: https://your-project.pages.dev

Option 2: Netlify

  1. Push your code to GitHub
  2. Go to https://netlify.com
  3. Click "New site from Git"
  4. Select your repository
  5. Configure:
    • Build command: (leave empty)
    • Publish directory: /
  6. Click "Deploy site"

Option 3: Vercel

# Install Vercel CLI
npm install -g vercel

# Deploy
vercel

Option 4: GitHub Pages

  1. Push your code to GitHub
  2. Go to repository Settings → Pages
  3. Select branch to deploy (e.g., main)
  4. Select root folder /
  5. Click "Save"

Your site will be available at: https://username.github.io/repository-name


Troubleshooting

Videos Not Loading

Problem: Videos don't appear in the playlist or won't play.

Solutions:

  1. Check browser console for errors
  2. Verify your API credentials in config.js
  3. Ensure Video IDs are correct
  4. Check CORS settings in Cloudflare
  5. Verify your Cloudflare Stream subscription is active

API Authentication Errors

Problem: 401 or 403 errors in console.

Solutions:

  1. Regenerate your API token
  2. Verify token has correct permissions (Stream:Read)
  3. Check Account ID is correct
  4. Ensure token hasn't expired

Player Controls Not Working

Problem: Play/pause or other controls don't respond.

Solutions:

  1. Check browser console for JavaScript errors
  2. Ensure all JS files are loaded correctly
  3. Try in a different browser
  4. Clear browser cache
  5. Check for JavaScript conflicts

Styling Issues

Problem: Page looks broken or unstyled.

Solutions:

  1. Verify all CSS files are loading
  2. Check file paths are correct
  3. Clear browser cache
  4. Check browser developer tools for CSS errors

CORS Errors

Problem: Cross-Origin Resource Sharing (CORS) errors.

Solutions:

  1. Serve the site via HTTP server (not file://)
  2. Configure CORS in Cloudflare Stream settings
  3. Use signed URLs for restricted content

Mobile Responsiveness Issues

Problem: Site doesn't display correctly on mobile.

Solutions:

  1. Check viewport meta tag is present
  2. Test on multiple devices
  3. Use browser developer tools' device emulation
  4. Check for fixed-width elements

Advanced Configuration

Custom Domains

To use a custom domain with Cloudflare Pages:

  1. Add your domain in Cloudflare Pages settings
  2. Update DNS records
  3. Enable HTTPS (automatic with Cloudflare)

Video Analytics

Track video engagement:

// Get analytics for a video
const analytics = await api.getVideoAnalytics('video-id');
console.log(analytics);

Signed URLs

For private content, use signed URLs:

// Generate signed URL (requires API implementation)
const signedUrl = await api.getSignedUrl('video-id', {
    exp: Date.now() + 3600000 // 1 hour
});

Subtitles and Captions

Add subtitles via Cloudflare dashboard:

  1. Go to video details
  2. Click "Captions"
  3. Upload WebVTT file
  4. Enable in player configuration

Performance Optimization

Image Optimization

  • Use WebP format for thumbnails
  • Lazy load playlist images
  • Use Cloudflare Image Resizing

Code Optimization

  • Minify CSS and JavaScript in production
  • Enable gzip/brotli compression
  • Use CDN for static assets

Caching

  • Set appropriate cache headers
  • Use Cloudflare's caching rules
  • Implement service workers for offline support

Security Best Practices

  1. Never commit API credentials to version control
  2. Use environment variables for sensitive data
  3. Implement rate limiting for API calls
  4. Use signed URLs for protected content
  5. Enable HTTPS everywhere
  6. Sanitize user inputs if adding comments/features
  7. Keep dependencies updated

Support and Resources

Official Documentation

Community

Video Streaming Resources


Next Steps

After completing the basic setup:

  1. ✅ Customize the theme and colors
  2. ✅ Add your own branding
  3. ✅ Implement user authentication (if needed)
  4. ✅ Add commenting system
  5. ✅ Integrate analytics (Google Analytics, etc.)
  6. ✅ Create admin panel for video management
  7. ✅ Add search functionality
  8. ✅ Implement playlists and categories

License

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

Contributing

Contributions are welcome! Please feel free to submit issues or pull requests.


Happy Streaming! 🎥

For questions or issues, please open an issue on GitHub or contact support.