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

Our $2B Valuation

By
Blackstone Growth Invests in Cloudinary

When we started our journey in 2012, we were looking to improve our lives as developers by making it easier for us to handle the arduous tasks of handling images and videos in our code. That initial line of developer code has evolved into a full suite of media experience solutions driven by a mission that gradually revealed itself over the course of the past 10 years: help companies unleash the full potential of their media to create the most engaging visual experiences.

Read more
Direct-to-Consumer E-Commerce Requires Compelling Visual Experiences

When brands like you adopt a direct–to-consumer (DTC) e-commerce approach with no involvement of retailers or marketplaces, you gain direct and timely insight into evolving shopping behaviors. Accordingly, you can accommodate shoppers’ preferences by continually adjusting your product offering and interspersing the shopping journey with moments of excitement and intrigue. Opportunities abound for you to cultivate engaging customer relationships.

Read more
Automatically Translating Videos for an International Audience

No matter your business focus—public service, B2B integration, recruitment—multimedia, in particular video, is remarkably effective in communicating with the audience. Before, making video accessible to diverse viewers involved tasks galore, such as eliciting the service of production studios to manually dub, transcribe, and add subtitles. Those operations were costly and slow, especially for globally destined content.

Read more
Cloudinary Helps Minted Manage Its Image-Generation Pipeline at Scale

Shoppers return time and again to Minted’s global online community of independent artists and designers because they know they can count on unique, statement-making products of the highest quality there. Concurrently, the visual imagery on Minted.com must do justice to the designs into which the creators have poured their hearts and souls. For Minted’s VP of Engineering David Lien, “Because we are a premium brand, we need to ensure that every single one of our product images matches the selected configuration exactly. For example, if you pick an 18x24 art print on blue canvas, we will show that exact combination on the hero images in the PDF.”

Read more
Highlights on ImageCon 2021 and a Preview of ImageCon 2022

New year, same trend! Visual media will continue to play a monumental role in driving online conversions. To keep up with visual-experience trends and best practices, Cloudinary holds an annual conference called ImageCon, a one-of-a-kind event that helps attendees create the most engaging visual experiences possible.

Read more