Cloudinary Blog

How to Serve Videos in Next.js Applications With Cloudinary

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

Overlaying Glasses Or Masks on Avatars With Vue.js and Cloudinary

Deep learning, a subset of machine learning, breaks down tasks in ways that make all kinds of machine assists possible. With deep learning, you can identify images by machine, i.e., instead of hand-coding software with specific instructions for a task, you train the machine with large amounts of data and algorithms that enable it to learn how to perform the task.

Read more
On-Demand Viewing of Live Video Presents New Opportunities

In early 2020, Cloudinary was planning its fourth annual ImageCon conference, a two-day event in the heart of San Francisco, where we’d congregate with curious digital-media minds to brainstorm best practices for media management. Instead, the COVID-19 pandemic forced the entirety of ImageCon 2020 online. As with all other events being planned, we had to overhaul the content to be communicated on video. Gratifyingly, we found the right partner—the event platform Bizzabo—to turn that into a reality.

Read more
Why the Future of E-commerce Is Live

In a previous post, I discussed how “going live” is gaining popularity across industries and verticals. What began as a way for gamers to jam together has evolved into a medium for broader entertainment and business purposes. To continue the conversation, this post unpacks the current trends of shoppable live streams to shine a light on how brands are leveraging “lives” to connect with shoppers in new ways.

Read more
An Overview of Live-Streaming Video Trends

“Let’s go live.” For decades, that’s what newscasters say as they cut to real-time footage of a colleague reporting in the field. The live-video feed adds visual interest and perspective to a story beyond what can be communicated by someone sitting behind the news desk. In the same way, live-streaming video nowadays adds context to other consumer environments. From gaming and events to shopping and social media, “going live” enhances everyday experiences, and it’s something anyone can do with relative ease.

Read more