Cloudinary Blog

How to Serve Videos in Next.js Applications With Cloudinary

By William Imoh
How to Serve Videos in Next.js Web Apps With Cloudinary

Videos are a powerful visual medium that fosters engagement by adding emotions and empathy. Web developers are often required to work with videos for websites or applications and must be equipped with the relevant knowledge and expertise.

This article shows you how to add videos to a Next.js app with Cloudinary.

Next.js is a React-based front-end development framework that enables functionalities like server-side rendering, static site generation, file-system routing (with no need to manually configure react-router-dom), and API endpoints for back-end features.

Cloudinary is a platform on which you can quickly and easily upload, store, manage, transform, and deliver images and videos for websites and apps. The platform offers a vast collection of SDKs for front-end frameworks and libraries.

Prerequisites

To follow the steps in this article, you must know the basics of React.js. You also need the following:

  • A web browser, such as Chrome, Edge, or Safari.
  • Access to CodeSandbox, an online editor for software development.
  • A Cloudinary account for video upload. Signup is completely free.

The Process

You can serve videos with Cloudinary on Next.js webpages in either of these two ways:

  • With the cloudinary-react library, which smoothly handles runtime rendering and offers native video functionalities with the innerRef properties. This library does not require a dynamic import.
  • With the JavaScript SDK of cloudinary-video-player and the cloudinary-core library. cloudinary-video-player offers Cloudinary’s functionalities and built-in methods, including robust options for serving videos. Working with the player requires more code and a dynamic import.

The sections below step you through both methods.

Method 1: With the cloudinary-react Library

First, go to https://codesandbox.io on a browser and click the Create Sandbox button. Enter Next.js in the Filter field and select a Next.js template from the search result. CodeSandbox will then scaffold a Next.js project.

Installing the Project Dependencies

Cloudinary offers an SDK for React developers to integrate images and videos into their apps. To install a dependency on codesandbox, navigate to the Dependencies section, type in the library name (cloudinary-react in this case), and select it to install.

Installing cloudinary-react

Configuring the Cloudinary Component

Create a components folder in the Files directory and, in the folder, create a VideoPlayer.js file with a VideoPlayer component, as shown below:

Copy to clipboard
import { useRef } from "react";
import { Video, CloudinaryContext } from "cloudinary-react";
const VideoPlayer = () => {
  const videoRef = useRef();
  return (
    <CloudinaryContext cloud_name="codedog">
      <div>
        <Video
          publicId="videoplayer-demo"
          width="100%"
          controls
          innerRef={videoRef}
        />
      </div>
    </CloudinaryContext>
  );
};
export default VideoPlayer;

The VideoPlayer component does the following:

  • Import the required dependencies and create a videoRef variable that gives the video component access to native HTML DOM methods and properties.
  • Configure CloudinaryContext as a wrapper with cloud_name (the name of your Cloudinary account). You can think of CloudinaryContext as a parent that passes all its traits and genes to its offspring. The nested children then automatically have all the properties defined in the parent.

Note
To get the value of cloud_name, log in to your Cloudinary account, navigate to the dashboard, and copy the value, as shown in the highlighted section below.

The Video element in the component contains the following:

  • publicId, which is a unique identifier with which Cloudinary generates the video URL.
  • controls, which includes HTML video functionalities like play, pause, etc.
  • innerRef, which accesses video functionalities through the videoRef variable you created earlier.

Ruby:
Copy to clipboard
cl_image_tag("dog.wav", :resource_type=>"video")
PHP v1:
Copy to clipboard
cl_image_tag("dog.wav", array("resource_type"=>"video"))
PHP v2:
Copy to clipboard
(new VideoTag('dog.wav'));
Python:
Copy to clipboard
CloudinaryVideo("dog.wav").image()
Node.js:
Copy to clipboard
cloudinary.image("dog.wav", {resource_type: "video"})
Java:
Copy to clipboard
cloudinary.url().resourceType("video").imageTag("dog.wav");
JS:
Copy to clipboard
cloudinary.videoTag('dog.wav').toHtml();
jQuery:
Copy to clipboard
$.cloudinary.image("dog.wav", {resource_type: "video"})
React:
Copy to clipboard
<Video publicId="dog.wav" resourceType="video">

</Video>
Vue.js:
Copy to clipboard
<cld-video publicId="dog.wav" resourceType="video">

</cld-video>
Angular:
Copy to clipboard
<cl-video public-id="dog.wav" resource-type="video">

</cl-video>
.NET:
Copy to clipboard
cloudinary.Api.UrlVideoUp.BuildImageTag("dog.wav")
Android:
Copy to clipboard
MediaManager.get().url().resourceType("video").generate("dog.wav");
iOS:
Copy to clipboard
cloudinary.createUrl().setResourceType("video").generate("dog.wav")
An example of a media URL and public ID

Using the Component

Now add the following code to the index.js file to use the Cloudinary component:

Copy to clipboard
import Head from "next/head";
import VideoPlayer from "../components/VideoPlayer";
export default function IndexPage() {
  return (
    <div>
      <Head>
        <title>Video Player with Cloudinary</title>
        <link rel="icon" href="/favicon.ico" />
      </Head>
      <header>
        <h1>Video Player</h1>
      </header>
      <section className={styles.description}>
        <p>
          There is no one who loves pain itself, who seeks after it and wants to
          have it
        </p>
      </section>
      <section>
        <VideoPlayer />
      </section>
    </div>
  );
}

You can now see the newly generated content and play the video.

Method 2: With the JavaScript SDK of the Cloudinary Video Player and the cloudinary-core Library

For this method, you use the same CodeSandbox you created earlier but comment out the VideoPlayer component.

Installing the Project Dependencies

Just as you did earlier, navigate to the Dependencies section and install cloudinary-video-player and the cloudinary-core library.

To run cloudinary-video-player, you need Node.js version 12 and above. For details on how to change CodeSandbox’s Node.js version, see the CodeSandbox documentation.

Configuring the cloudinary-core Component Next, go to the components folder and create a components/NativeVideoPlayer.js file. Add the following code to configure Cloudinary:

Copy to clipboard
import "cloudinary-video-player/dist/cld-video-player.min.js";
import "cloudinary-video-player/dist/cld-video-player.min.css";
import { Cloudinary } from "cloudinary-core";
import { useEffect } from "react";
const NativeVideoPlayer = () => {
  const cld = new Cloudinary({ cloud_name: "chuloo" });
  useEffect(() => {
    const videoPlayer = cld.videoPlayer("video-player", {
      muted: true,
      controls: true
    });
    videoPlayer.source("video-blog/cat");
  });
  return (
    <div>
      <video id="video-player" />
    </div>
  );
};
export default NativeVideoPlayer;

The above code performs these tasks:

  • Import the required dependencies.
  • Create and configure a Cloudinary instance with your cloud name.
  • Configure the Cloudinary instance with an ID (required by the SDK of the Cloudinary Video Player), mute the player, activate the controls, and specify the source.

Finally, the code returns a native HTML <video> element with the video-player instance.

Using the Component

Now add the following code to the index.js file to use the cloudinary-core component:

Copy to clipboard
import Head from "next/head";
import styles from "../styles/Home.module.css";
import VideoPlayer from "../components/VideoPlayer";
import dynamic from "next/dynamic"; //add

//add
const NativeVideo = dynamic(
  () => import("../components/NativeVideoPlayer"),
  { ssr: false }
);
export default function IndexPage() {
  return (
    <div className={styles.container}>
      <Head>
        <title>Video Player with Cloudinary</title>
        <link rel="icon" href="/favicon.ico" />
      </Head>
      <header className={styles.header}>
        <h1>Video Player</h1>
      </header>
      <section className={styles.description}>
        <p>
          There is no one who loves pain itself, who seeks after it and wants to
          have it
        </p>
      </section>
      <section className={styles.video_player}>
        {/* <VideoPlayer /> */}
        <NativeVideo />
      </section>
    </div>
  );
}

The above code does the following:

  • Import dynamic, the built-in support in Next.js for dynamically working with JavaScript modules.
  • Create a DynamicVideo variable to dynamically import NativeVideoPlayer on runtime and avoid any errors thrown by the browser’s window object.
  • Render DynamicVideo as a component.

You can now see the newly generated video.

Conclusion

Serving videos with Cloudinary on Next.js webpages is a seamless, intuitive process. For more details on the code examples cited in this post, see the complete source code on CodeSandbox.

Recent Blog Posts

New for DAM: Media Library Extension for Chrome

By Sharon Yelenik
A New Media Library Chrome Extension for Cloudinary DAM

With the introduction of the Media Library Extension, a Chrome-browser add-on that streamlines the access to, search for, and management of images and videos, Cloudinary offers yet another effective tool for its Digital Asset Management (DAM) solution. Let’s have a look at how most teams are currently working with media assets and how the new add-on not only boosts efficiency, but also renders the process a pleasure to work with.

Read more
New Features Supercharge Cloudinary’s Digital Asset Management Solution.

Today, I’m thrilled to announce the launch of Apps for Digital Asset Management and a Media Library Extension for the Chrome browser, which enables easy, flexible integration with all web-based applications in addition to making asset discovery more robust and accessible to all.

Read more
Scale and Automate Workflows With Modern Digital Asset Management Systems

With building, growing, and maintaining a strong digital presence being a top priority for all brands, high-quality visual content is paramount. In fact, consumers are 40 times more likely to share visual content on social networks than on other forums. Plus, a recent study from Wyzowl found that 84% of consumers made purchase decisions after watching a video, which explains why many brands are adding more and more visual media to their sites.

Read more
Speed Up Your Website With No Code Through Cloudinary’s Media Optimizer

As website and mobile apps rely more on visual media to create engaging user experiences, delivering strong web and app performance becomes more challenging for developers. The faster your site, the more time visitors would spend on it. Conversely, the slower the site, the higher the bounce rate, and the lower Google ranks it in SEO.

Read more
Bizzabo Holds Virtual and Simulive Events and Delivers VOD

While facing the pandemic-induced setbacks to its live-events business in the past two years, our customer and event innovator Bizzabo decided to reshape its offering into a digital-first Event Experience OS that fosters human connections and generates excitement. Toward that end, Bizzabo turned to Cloudinary for support of high-performance, visual events for large audiences to replace or augment live shows.

Read more