Features

Developers

How to upload a video with React and NodeJS

June 9, 2022 - Yohann Martzolff in Delegated Upload, API client, Video upload, JavaScript, React, NodeJS, Next.js

Uploading a video to api.video can be done in several ways:

  • API: make calls to get the mandatory information such as access token, create your fully customized video container, and finally upload your video file ๐Ÿง‘โ€๐Ÿ’ป. Itโ€™s the most secure way to upload, but it requires a backend to hide sensitive data and several API calls. Even though itโ€™s easy, customizable, and reliable, you may need a faster way to do this.
  • TypeScript uploader: api.video provides a TypeScript uploader that allows you to upload video directly to your workspace without calling the API. You can even choose between three upload methods ๐Ÿคฉ! Donโ€™t forget you still have to implement a UI for your uploader if itโ€™s not already done!
  • React upload button: a few weeks ago, we quietly released the first version of our React upload button on NPM.js. This new package allows you to display a fully customizable button in your application in less than a minute! Today, we will see together how to get mandatory information from a Node backend to use this React component without exposing any sensitive data ๐Ÿ”’.

Prerequisites

  • React and NodeJS knowledge
  • For the simplicity of this example, weโ€™ll use Next.js, a React framework that provides an already implemented Node server. Basic knowledge of it can help you go through this tutorial.

Remember that any Node backend will work to get information, as seen in this article.

Get started

You need an api.video account to work with our API and our packages.

Create a free one or log into yours just here.

1. Create a new Next.js application

From your command line, run one of the below commands:

yarn create next-app --typescript
# or
npx create-next-app@latest --ts

Once completed, open your new Next.js application in your favorite IDE and run it:

yarn dev
# or 
npm run dev
Next.js new application

2. Get the required packages

To complete this tutorial, weโ€™ll need two api.video packages ๐Ÿ› ๏ธ

  • NodeJS client package: to access the API with ease
  • React upload button: to upload our videos

From your application root, run this command:

yarn add @api.video/nodejs-client @api.video/react-upload-button
# or
npm install @api.video/nodejs-client @api.video/react-upload-button

3. Create a .env.development file

Create a .env.development file at the root of your application and store two environment variables in it:

  • The Next.js public API host: to access the implemented Node.js API from Next
  • Your API key value: to instantiate the Node.js client from api.video
NEXT_PUBLIC_HOST=http://localhost:3000
API_KEY=YOUR_API_KEY

You can find your API key in the API keys section of the api.video dashboard.

Get your API key

โš ๏ธ You need to restart your application each time youโ€™ve made changes in your .env.development. Otherwise, you cannot access new environment values.

4. Create your API endpoint

In this part, we want to create one API endpoint that allows us to make two actions:

  • Retrieve our upload tokens list
  • Create one if needed

To do this, we will differentiate the calls to this endpoint by HTTP methods:

  • GET to retrieve our upload tokens list
  • POST to create one upload token

Create a new file under the /pages/api directory in your application and name it uploadTokens.ts

Application project tree

Retrieve your upload tokens list

In your brand new uploadTokens.ts file, create your endpoint and the method to retrieve your upload tokens list. Copy and paste the code below:

import ApiVideoClient from '@api.video/nodejs-client'
import type { NextApiRequest, NextApiResponse } from 'next'

export default async function handler(
  req: NextApiRequest,
  res: NextApiResponse
) {
  try {
    const client = new ApiVideoClient({
      apiKey: process.env.API_KEY // It retrieves your API key from .env.development
    })
    if (req.method === 'GET') {
      const uploadTokensList = await client.uploadTokens.list()
      res.status(200).json({ uploadTokensList })
    }
    else res.status(405).send('METHOD NOT ALLOWED')
  } catch (error) {
    res.status(401).send(error)
  }
}

Find the official documentation for the upload tokens list method here.

Create a new upload token

We may need to generate a new upload token if we donโ€™t have any available. Add the creation method in your uploadTokens.ts file:

if (req.method === 'GET') // ...
else if (req.method === 'POST') {
  const newUploadToken = await client.uploadTokens.createToken()
  res.status(200).json({ newUploadToken })
} 
else // ...

Find the official documentation for the upload token createToken method here.

5. Call your API

Now we can retrieve our upload tokens list and generate a new one on demand. Weโ€™ll see how to make it happens from the front end.

Letโ€™s clean our Home component ๐Ÿงน Go to your pages/index.tsx file and modify it:

import type { NextPage } from 'next'
import Head from 'next/head'
import styles from '../styles/Home.module.css'
import { UploadButton } from '@api.video/react-upload-button'

const Home: NextPage = () => {
	const [uploadToken, setUploadToken] = useState<string | undefined>(undefined)

  return (
    <div className={styles.container}>
      <Head>
        <title>My Upload App</title>
        <meta name="description" content="Generated by an awesome developer" />
        <link rel="icon" href="/favicon.ico" />
      </Head>

      <main className={styles.main}>
        <h1 className={styles.title}>
          Welcome to my Upload application!
        </h1>

				{/* Displays an upload button */}
        {uploadToken && <UploadButton uploadToken={uploadToken}>Click Me To Upload A Video ๐Ÿš€</UploadButton>}
      </main>
    </div>
  )
}

export default Home

Now our app is nice and clean, letโ€™s implement our logic in 2 steps:

  • We want to check if we have any available upload tokens from our upload tokens list.
  • If we do not have any upload token, we want to create one.

Set your upload token

Create a new method that calls your API endpoint uploadTokens to retrieve your list, and create one if the list is empty. You should call it in a useEffect inside your Home component:

Call the method in a useEffect inside your Home component:

const Home: NextPage = () => {
	// ...

  useEffect(() => {
    const instantiateUploadToken = async (): Promise<void> => {
      // Retrieve your upload tokens list
      const list: TokenListResponse = await fetch(
        `${process.env.NEXT_PUBLIC_HOST}/api/uploadTokens`,
        {
          method: 'GET',
        }
      )
      .then(res => res.json())
    
      // If an upload token is available
      if (list.data.length > 0) {
        setUploadToken(list.data[0].token)
        return
      }
    
      // If we do not have any upload token available, we create one
      const newUploadToken: UploadToken = await fetch(
        `${process.env.NEXT_PUBLIC_HOST}/api/uploadTokens`,
        {
          method: 'POST',
        }
      )
      .then(res => res.json())
      setUploadToken(newUploadToken.token)
    }
    instantiateUploadToken()
  }, [])

	// ...
}

6. Click. Itโ€™s magic! ๐Ÿงš

Already? ๐Ÿ˜ฑ

Everything should work well now. Click on the displayed button in your application and choose a file to upload to your api.video workspace.

The upload application

7. Customize your upload button ๐Ÿ’…

You can customize multiple things to make your upload button unique:

  • CSS: make it looks the way you want
  • Progress event: trigger a callback on upload progress
  • Success event: trigger a callback on upload success
  • Error event: trigger a callback on upload error

Check our complete list of examples for inspiration ๐Ÿง˜

Yohann Martzolff

Front-end Engineer

Create your free account

Start building with video now