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

Partner news: Cloudinary-Getty Images Integration

Supported by intelligent automation, Cloudinary serves as an effective conduit between media asset management and delivery so you can take maximum advantage of assets, compress workflows, and build and coordinate engaging and inspiring customer experiences. Through Cloudinary’s Digital Asset Management (DAM) solution, which employs the company’s innovative image and video APIs, creative and marketing teams can benefit from them, as well as from many AI-powered and automated capabilities. As a result, you can transform, optimize, and deliver media at scale on an intuitive UI.

Read more
Why Audio in Video Matters

Many content creators and consumers tend to regard video as visuals, but that’s only part of the experience. Immersive video content includes strong audio. Just like in a movie, the audio for video content comprises many components: the narrator or subjects, the background music that sets the mood and draws viewers in, sound effects, and so forth.

Read more

For Developers: the HTML <picture> Element Explained

By Amarachi Amaechi
For Developers: the HTML <picture> Element Explained

We all know the good ol', tireless <img> element, which has been a long-time go-to for inserting graphics into webpages. Time doesn’t stop, however, and neither do technological advancements. So, let’s get you up to speed with the element’s modern alternative: the <picture> element.

Read more