Key takeaways:
- A basic Next.js video player is a native video element inside a component. Put small files in public/ or point src at a hosted URL, then add controls, muted, playsInline and poster as needed.
- Projects created with create-next-app today use the App Router by default, so the home page is app/page.tsx (or app/page.js), and any component with state, event handlers or browser APIs needs the ‘use client’ directive.
- Custom play, seek, volume and fullscreen controls come from the HTMLMediaElement and Fullscreen APIs, wired to a ref in a client component.
- For adaptive streaming and automatic optimization, next-cloudinary’s CldVideoPlayer embeds the Cloudinary Video Player and can play HLS through a streaming profile.
Social media is increasingly dominated by video content–over 85% of people on the internet watch videos online each month. Video content, prevalent across platforms from social media to streaming services, is highly effective at grabbing and holding viewers’ attention. When your video loads slowly, keeps buffering and doesn’t work as it should, you might end up losing the audience’s interest.
While it is easier to embed a YouTube video, building a customized Feature-Rich Next.js video player can give you more control over playback, customization, and performance. In this article, you’ll learn everything you need to know about building a Next.js video player, and how Cloudinary can streamline the process for you.
In this article:
- What is Next.js and Why Use it for Video Playback?
- Setting Up a Basic Video Player in Next.js
- Enhancing the Next.js Video Player with Custom Features
- Native Video, hls.js or CldVideoPlayer: Which Should You Use?
- Optimizing the Next.js Video player with Cloudinary
- Make an Impact with the Next.js Video Player
What is Next.js and Why Use it for Video Playback?
Next.js is a React-based platform designed for high-performance, efficient web development. It has features like server-side rendering and static site generation that improve SEO and boosts site speed. These capabilities make it an excellent framework for building high-performing applications.
So, when it comes to the Next.js video player, it shines due to the quick load times and efficient rendering that ensures videos play with no delays. Plus, Next.js works well with image optimization and media platforms, making it a perfect fit for media-rich applications. If you’re looking to stream tutorials or host a video content library, Next.js is the right framework that makes everything look seamless.
Setting Up a Basic Video Player in Next.js
Getting started with the video player in Next.js is simple and doesn’t require you to have any advanced skills. In this section, we’ll guide you through the process of creating a functional HTML5 video player in the Next.js application.
Create a New Next.js Project
Step 1: Check if you have Node.js installed on your machine. If not, you can download it from nodejs.org.
Step 2: Open your terminal and run the following command to create a new Next.js project:
npx create-next-app@latest my-video-player
Step 3: After creating the project, navigate to the project directory:
cd my-video-player
Step 4: Run the development server to check if everything is works correctly:
npm run dev
Visit http://localhost:3000 in your browser. You should see the default Next.js welcome page.
2. Adding a Simple HTML5 Video Player
Now, let’s create the video player component. We’ll create a new component for the video player and use the <video> element with some basic attributes to enhance its functionality.
Step 1: Inside your project, create a components folder if it doesn’t already exist. Then, inside the components folder, create a new file called VideoPlayer.js.
mkdir components touch components/VideoPlayer.js
Step 2: Open the VideoPlayer.js file and add the following code:
// components/VideoPlayer.js
export default function VideoPlayer() {
return (
<div>
<video controls width="100%">
<source src="/sample-video.mp4" type="video/mp4" />
Your browser does not support the video tag.
</video>
</div>
);
}
Step 3: Put your video file in the public folder of your Next.js project. For example, add a file named sample-video.mp4 to the public folder. The src attribute in the <source> tag points to the video file in the public folder. In Next.js, files in the public folder are served statically at the root URL (/).
Step 4: Now, let’s use the VideoPlayer component in a page. Open the app/page.tsx (app/page.js if you created a JavaScript project; pages/index.js applies only to the older Pages Router) and modify it as follows:
// pages/index.js
import VideoPlayer from '../components/VideoPlayer';
export default function Home() {
return (
<div>
<h1>My Next.js Video Player</h1>
<VideoPlayer />
</div>
);
}
Step 5: Now, start your Next.js development server with npm run dev and visit http://localhost:3000 in your browser. You should see the video player with your video loaded and ready to play.
Attributes like loop, autoplay, control, and muted give users control over the enhancement of the usability of the player and the playback. Let’s take a quick look at what each of these does:
controlsAdds default video controls like play, pause, volume, and fullscreen.autoplayStarts playing the video automatically when the page loads.
Note: Many browsers block autoplay with sound for a better user experience. Use “muted” with “autoplay” to ensure it works.loopLoops the video continuously.mutedMutes the video by default. Useful for autoplay scenarios.posterSpecifies an image to show as a thumbnail before the video plays.
3. Loading Video Files
Now you’re ready to load your videos, and you can source the videos from either external URLs or locally.
- Local Files: In the public folder, place your video, e.g., public/sample-video.mp4, and give it a reference with the relative path, for example, /sample-video.mp4.
- External URLs: Replace the src attribute with a link to your hosted video, like
https://example.come/video.mp4
To ensure compatibility across all the major browsers, make sure that your videos are in the formats that are common like MP4, Ogg, and WebM.It ensures that the payback is smooth for all your users, irrespective of the device or browser they are using.
Enhancing the Next.js Video Player with Custom Features
To truly stand out with your Next.js application, you can enhance the video player with custom features that improve functionality and user engagement. With these interactive elements like custom controls, playback speed adjustments, and progress bars, you can create a more robust and user-friendly experience.
1. Custom Play/Pause Button
Replacing the browser controls with play and pause buttons helps you design a video player that’s compatible with your application theme. You can create customized buttons and give your users an appealing way to interact with your player. These buttons are linked to the video’s playback to help with playing and pausing whenever needed.
2. Adding Volume Control and Seek Bar
A seek bar and volume controls help you create user-friendly sliders that allow viewers to adjust audio and navigate through the video. The volume slider lets users adjust the audio levels, and the seek bar helps them jump to the parts of the video they want to watch.
JavaScript lets you have improved customization for your users to enjoy a smooth experience accessing different devices. These elements can also be modified based on user preference.
3. Implementing Fullscreen Mode
To enable full-screen mode in your video player, you need to provide users with an easy-to-use way to expand the video to fill their entire screen. This is usually achieved with a fullscreen button that, when clicked, triggers the browser’s fullscreen API. Full-screen mode enhances the viewing experience, making it especially useful for high-quality tutorials and immersive content.
The cross-browser compatibility is an important feature for the fullscreen to work with consistency. Every browser has a different way of entering fullscreen mode, and therefore, handling these variations is crucial by keeping a check on the browser-specific implementation. It ensures that users get a seamless full-screen experience across all browsers, be it Firefox, Chrome, or Safari.
4. Thumbnail Previews on Hover
To create a thumbnail preview feature, you’ll need to generate snapshots of the video and display them when users hover over the seek bar. This can be done by extracting frames from video at different intervals of time to show the corresponding thumbnails based on the cursor position of the user. Users can preview different scenes by referencing the seek bar’s position, which corresponds to specific timestamps.
How Do You Wire Custom Controls in the App Router?
The features above need browser APIs, so they belong in a client component. This one replaces the default controls with a play button, a seek bar, a volume slider and a fullscreen button, using the video element’s own methods and events:
// components/CustomPlayer.jsx
'use client';
import { useRef, useState } from 'react';
export default function CustomPlayer({ src }) {
const videoRef = useRef(null);
const [playing, setPlaying] = useState(false);
const [progress, setProgress] = useState(0);
const togglePlay = () => {
const video = videoRef.current;
if (video.paused) video.play();
else video.pause();
};
return (
<div>
<video
ref={videoRef}
src={src}
playsInline
onPlay={() => setPlaying(true)}
onPause={() => setPlaying(false)}
onTimeUpdate={(e) => {
const v = e.currentTarget;
setProgress(v.duration ? v.currentTime / v.duration : 0);
}}
style={{ width: '100%' }}
/>
<button onClick={togglePlay}>{playing ? 'Pause' : 'Play'}</button>
<input
type="range" min="0" max="1" step="0.001" value={progress}
aria-label="Seek"
onChange={(e) => {
const v = videoRef.current;
v.currentTime = Number(e.target.value) * v.duration;
}}
/>
<input
type="range" min="0" max="1" step="0.05" defaultValue="1"
aria-label="Volume"
onChange={(e) => { videoRef.current.volume = Number(e.target.value); }}
/>
<button onClick={() => videoRef.current.requestFullscreen()}>Fullscreen</button>
</div>
);
}
Native Video, hls.js or CldVideoPlayer: Which Should You Use?
Most Next.js video players start from one of three setups. The right one depends on whether you need adaptive streaming and how much you want to build yourself:
| Feature | Native video element | Video element plus hls.js | CldVideoPlayer (next-cloudinary) |
|---|---|---|---|
| Adaptive streaming | No, one file at one quality (Safari can play HLS natively) | Yes, HLS in browsers with Media Source Extensions | Yes, HLS through a streaming profile |
| Controls and UI | Browser defaults, or your own as above | Your own | A customizable player UI with colors, fonts and logo |
| Video processing | You encode and host the files | You package HLS yourself | Cloudinary transcodes and delivers through its CDN |
| Best for | Short clips, backgrounds, simple pages | Teams with an existing HLS pipeline | Apps that want streaming and optimization without running a video pipeline |
Optimizing the Next.js Video Player with Cloudinary
Cloudinary is a media management platform that enhances video performance, delivery, and playback within the Next.js video player application. By integrating Cloudinary, developers can ensure a smooth playback across all browsers and devices.
Integrating Cloudinary with Next.js
First, set up a Cloudinary account and install the Cloudinary npm package in your Next.js project. By integrating Cloudinary with your video player, you’ll be able to manage video uploads, apply transformations on the fly, and offer optimized video content to your users.
Cloudinary streamlines media management, making it easy to optimize videos for faster loading and adjust resolutions effortlessly. Whether you need compression, resizing, or format adjustments, Cloudinary does it all. This ensures your Next.js video player remains responsive, efficient, and delivers a smooth viewing experience.
Optimizing Video for Fast Loading and Streaming
With Cloudinary’s automatic optimization and compression, videos play faster without any loss of quality. Using transformations, videos are converted into modern formats that dynamically adjust resolution, resulting in smaller file sizes.
By using adaptive bitrate streaming, Cloudinary delivers high-quality video by automatically adjusting the quality based on network speed and avoiding buffering issues. It guarantees rapid delivery and top-notch streaming for each user via the Next.js video player.
Using Cloudinary’s AI Features for Auto-Generated Thumbnails
The AI-powered tools from Cloudinary can help generate automatic video thumbnails, making it easier to set up preview images with minimal manual effort. It selects the key frames by analyzing video content to ensure that thumbnails represent different scenes accurately.
Generating thumbnails with Cloudinary enhances video navigation with dynamic previews, thus enabling users to jump to specific points quickly. This automation improves the Next.js video player, saving time by eliminating the need for making thumbnails manually.
Customizing Video Quality and Resolution Based on Device
Cloudinary adjusts the format and quality of the videos automatically, ensuring that desktop users get high-resolution playback, whereas mobile users get a lighter version that is compatible with small screens. Such customization prevents buffering and reduces the load times. When you integrate Cloudinary into your Next.js video player, you can deliver a seamless viewing experience with no compromises on the video quality.
How Do You Add the Cloudinary Video Player to a Next.js App?
The next-cloudinary package wraps the Cloudinary Video Player in a React component. Install it with npm install next-cloudinary, then add your cloud name to .env.local:
NEXT_PUBLIC_CLOUDINARY_CLOUD_NAME=”<Your Cloud Name>”
Create a client component that imports the player and its CSS. The transformation and sourceTypes props request an HLS stream with the hd streaming profile, so viewers get adaptive bitrate playback:
// components/CloudinaryPlayer.jsx
'use client';
import { CldVideoPlayer } from 'next-cloudinary';
import 'next-cloudinary/dist/cld-video-player.css';
export default function CloudinaryPlayer({ publicId }) {
return (
<CldVideoPlayer
width="1920"
height="1080"
src={publicId}
transformation={{ streaming_profile: 'hd' }}
sourceTypes={['hls']}
/>
);
}
Render it from any page with <CloudinaryPlayer publicId=”my-video” />, using the public ID of a video in your Cloudinary account. The App Router needs the ‘use client’ directive here, as the next-cloudinary docs point out.
Make an Impact with the Next.js Video Player
To build a fully functional and feature-rich Next.js video player, you need a solid basic setup, custom controls, and performance optimizations. Integrating Cloudinary helps improve video delivery with automatic optimization and thumbnail generation.
With Cloudinary, your video player loads faster and performs consistently across different devices, enhancing the user experience. Developers can customize and fine-tune features to create a player that meets their specific needs.
Transform your videos instantly with Cloudinary’s powerful API tools. Sign up for a Cloudinary account today and see how easy it can be.
Frequently Asked Questions
How do I add a video to a Next.js page?
Use the HTML video element in a component. For a local file, place it in the public folder and set src to its path, such as /sample-video.mp4. For a hosted file, use its full URL. Add controls for the browser’s play bar, preload=”none” to avoid downloading before play, and a poster image so the player is not blank while it loads.
Does a Next.js video player need ‘use client’?
Only when the component uses state, event handlers or browser APIs. A plain video element with controls renders fine from a Server Component. Custom controls, refs, fullscreen buttons and players such as CldVideoPlayer run in the browser, so their file needs the ‘use client’ directive at the top. Keep the directive in the player component, not in the whole page.
Why won’t my video autoplay in Next.js?
Browsers block autoplay with sound, so a video with autoplay but without muted usually stays paused. Add muted alongside autoplay, and add playsInline, which Safari requires for autoplay. In JSX the attributes are autoPlay, muted and playsInline. Viewers can still turn the sound on from the controls once the video is playing.
Can a Next.js app play HLS streams?
Yes, but most browsers need help. Safari plays .m3u8 playlists natively in a video element. Chrome, Edge and Firefox need a JavaScript player built on Media Source Extensions, such as hls.js, or a player that includes HLS support, such as CldVideoPlayer with sourceTypes set to hls.