DEV Community

hamza rehman
hamza rehman

Posted on

🚀 1. Efficient Video Uploads to AWS S3 with React

The Problem with Base64 and Buffer Uploads
Many developers follow the approach of uploading videos to their backend as Base64 or Buffer and then transferring them to S3. While this works, it’s inefficient because:

It increases server workload.
Slows down the upload process.
May expose your backend to unnecessary risks.
The Better Solution: Pre-Signed URLs
Pre-signed URLs let users upload files directly to S3 without exposing your AWS credentials. It’s faster, more secure, and reduces backend processing.

Image description

Backend: Generating Pre-Signed URLs
Here’s how you can create a pre-signed URL using aws-sdk in a Node.js backend:

const AWS = require('aws-sdk');
const express = require('express');
const app = express();

AWS.config.update({
  accessKeyId: 'YOUR_ACCESS_KEY',
  secretAccessKey: 'YOUR_SECRET_KEY',
  region: 'YOUR_REGION',
});

const s3 = new AWS.S3();

app.get('/generate-presigned-url', (req, res) => {
  const params = {
    Bucket: 'your-bucket-name',
    Key: `${Date.now()}-${req.query.filename}`,
    Expires: 60, // URL valid for 60 seconds
    ContentType: req.query.contentType,
  };

  s3.getSignedUrl('putObject', params, (err, url) => {
    if (err) {
      return res.status(500).json({ error: 'Error generating URL' });
    }
    res.json({ url });
  });
});

app.listen(5000, () => {
  console.log('Server running on port 5000');
});

Enter fullscreen mode Exit fullscreen mode

Frontend: Uploading Videos Directly to S3
In your React app, use the pre-signed URL to upload files directly to S3. This bypasses your backend entirely for the upload step.

import axios from 'axios';

const uploadToS3 = async (file) => {
  const response = await fetch(`/generate-presigned-url?filename=${file.name}&contentType=${file.type}`);
  const { url } = await response.json();

  await axios.put(url, file, {
    headers: { 'Content-Type': file.type },
  });

  console.log('File uploaded successfully');
};

const handleFileUpload = async (event) => {
  const file = event.target.files[0];
  if (file) {
    await uploadToS3(file);
  }
};

Enter fullscreen mode Exit fullscreen mode

🌟 2. Streaming Videos Like a Pro
Why Adaptive Streaming?
Using adaptive streaming (HLS) ensures smooth playback across different network conditions. HLS creates .m3u8 files that allow players to adjust the video quality dynamically.

Convert Videos to HLS
Use AWS tools like:

AWS Elastic Transcoder
AWS Elemental MediaConvert
These services convert uploaded videos into HLS format for adaptive streaming.

Serve Videos via CloudFront
Integrate Amazon CloudFront with your S3 bucket to enable global content delivery. CloudFront caches your videos at edge locations, reducing buffering for users worldwide.

React Video Playback
Use react-player or video.js to play .m3u8 files in your React app. Here’s an example:

import ReactPlayer from 'react-player';

const VideoPlayer = () => {
  return (
    <div className="video-player">
      <ReactPlayer
        url="https://your-cloudfront-url/video.m3u8"
        controls
        width="100%"
        height="100%"
      />
    </div>
  );
};

export default VideoPlayer;

Enter fullscreen mode Exit fullscreen mode

🎯 3. Why This Approach Works
1.Faster Uploads: Direct S3 uploads minimize backend involvement.
2.Scalable Playback: Adaptive streaming ensures smooth video playback, even on slow networks.
3.Global Reach: CloudFront reduces latency for users worldwide.
4.Cost-Effective: Process videos once and serve them efficiently.

💬 What’s Your Approach?
I’d love to hear how you handle video uploads and streaming in your projects. Are you using AWS, or have you explored other tools? Let’s discuss and share best practices in the comments! 🙌

Image of Timescale

🚀 pgai Vectorizer: SQLAlchemy and LiteLLM Make Vector Search Simple

We built pgai Vectorizer to simplify embedding management for AI applications—without needing a separate database or complex infrastructure. Since launch, developers have created over 3,000 vectorizers on Timescale Cloud, with many more self-hosted.

Read full post →

Top comments (0)

Image of Docusign

🛠️ Bring your solution into Docusign. Reach over 1.6M customers.

Docusign is now extensible. Overcome challenges with disconnected products and inaccessible data by bringing your solutions into Docusign and publishing to 1.6M customers in the App Center.

Learn more