Hygraph is a headless CMS that offers flexibility in how content, including video, is managed. It decouples content management from presentation, allowing for easy integration into various platforms while maintaining a structured and scalable solution. To efficiently manage video content and metadata, you can set up a Hygraph project tailored for video storage, querying, and playback.
Create a Hygraph Account and Set Up a Project
To get started with Hygraph, you first need to create an account on the Hygraph platform:
Step 1: Go to Hygraph and sign up for a new account.
Step 2: After signing up, create a new project from your dashboard.
Step 3: Choose the project type based on your content requirements.
Defining Content Models
Content models structure how your video data is organized within Hygraph. By defining a custom model, you can efficiently manage video-related data, such as metadata, video URLs, and associated assets like thumbnails.
Example: Creating a Video Content Model
Here's how to define a basic Video content model:
Step 1: In the Hygraph dashboard, navigate to the Content Model section.
Step 2: Create a new content model called Video.
Step 3: Add the following fields to the Video model, including Title (Text field), Description (Text field), Video URL (URL field), and Thumbnail (Asset field).
The content model should look like this:
{
"title": "Sample Video Title",
"description": "This is a sample description of the video.",
"videoUrl": "https://yourcdn.com/video.mp4",
"thumbnail": "https://yourcdn.com/video-thumbnail.jpg"
}Connecting to the Hygraph API
Hygraph uses GraphQL, allowing you to efficiently fetch and manage video data. The next step is connecting your frontend to Hygraph to query the video data.
Example: Fetching Video Data Using GraphQL
To fetch the video details from Hygraph using GraphQL, follow these steps:
1. Generate a GraphQL endpoint from the Hygraph dashboard under API Access.
2. Use the following GraphQL query to retrieve the video data:
query {
video {
title
description
videoUrl
thumbnail {
url
}
}
}
3. To query the data programmatically, you can use fetch() or a GraphQL client like Apollo Client. Here's an example using fetch() in JavaScript:
const fetchVideoData = async () => {
const response = await fetch('https://graphql-endpoint.com', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer YOUR_API_KEY',
},
body: JSON.stringify({
query: `
query {
video {
title
description
videoUrl
thumbnail {
url
}
}
}
`,
}),
});
const data = await response.json();
return data.data.video;
};
fetchVideoData().then(video => {
console.log(video);
});
Explanation:
- fetchVideoData: Defines an asynchronous function to fetch video data from a GraphQL API.
- fetch('https://graphql-endpoint.com'): Sends a POST request to the specified GraphQL endpoint.
- method: 'POST': Specifies the HTTP method as POST for sending the query.
- Authorization: Includes a bearer token (YOUR_API_KEY) for authentication with the API.
- response.json(): Converts the response body into JSON format.
- return data.data.video: Returns the video object from the response data.
- fetchVideoData().then(video => { console.log(video); }): Calls the fetchVideoData function and logs the returned video data to the console.
Integrating Videos into Your Frontend
Once you have fetched video data from Hygraph, it's time to integrate the videos into your frontend application. Here, we"ll demonstrate how to embed a video using HTML5"s <video> element.
Example: Embedding Videos on a Webpage
Assuming you"ve fetched the video data, here"s an example of how you can embed the video into your webpage:
<video controls width="100%" height="auto">
<source src="https://yourcdn.com/video.mp4" type="video/mp4">
Your browser does not support the video tag.
</video>
Explanation:
- <video controls width="100%" height="auto">: Embeds a video player in the webpage with controls (play, pause, etc.), and sets the video width to 100% of the container and height to auto for maintaining aspect ratio.
- <source src="https://yourcdn.com/video.mp4" type="video/mp4">: Specifies the video source URL (video.mp4) and its MIME type (video/mp4).
To display the video dynamically, bind the video URL from the Hygraph response to the src attribute:
const displayVideo = (video) => {
const videoElement = document.querySelector('video');
videoElement.src = video.videoUrl;
};
fetchVideoData().then(displayVideo);
Explanation:
- const videoElement = document.querySelector('video'): Selects the first <video> element on the page.
- videoElement.src = video.videoUrl: Sets the src attribute of the selected video element to the videoUrl from the video object.
- fetchVideoData().then(displayVideo): Fetches video data asynchronously using fetchVideoData() and passes the resulting video object to the displayVideo function for display.
Using Webhooks for Video Updates
Hygraph"s webhook feature allows you to get notifications when video content is updated. This can be used to update your frontend automatically with the latest video content.
Example: Setting Up a Webhook
Step 1: In your Hygraph dashboard, navigate to Settings → > Webhooks and create a new webhook.
Step 2: Provide the URL where your application will listen for incoming webhook notifications.
Step 3: On your backend, set up an endpoint to handle the webhook payload:
app.post('/webhook', (req, res) => {
const { videoUrl, title } = req.body;
// Logic to update the frontend with new video data
console.log('Video updated:', title, videoUrl);
res.status(200).send('Received video update');
});
Explanation:
- app.post('/webhook', (req, res) => { ... }): Defines a POST route for the /webhook endpoint to handle incoming HTTP requests.
- const { videoUrl, title } = req.body: Destructures the videoUrl and title properties from the request body.
- console.log('Video updated:', title, videoUrl): Logs the updated video title and URL to the console for debugging or monitoring purposes.
- res.status(200).send('Received video update'): Sends an HTTP response with status code 200, indicating the request was successfully processed.
Storing Videos on Cloud Storage
Cloud storage services like AWS S3 are commonly used to store large video files. This allows for efficient management and retrieval of videos in a scalable manner.
Example: Uploading a Video to AWS S3
Step 1: Install the AWS SDK:
npm install aws-sdkExplanation: Installs the AWS SDK (Software Development Kit) package using npm (Node Package Manager) to interact with AWS services from a Node.js application.
Step 2: Use the AWS SDK to upload videos to S3:
const AWS = require('aws-sdk');
const s3 = new AWS.S3();
const uploadVideoToS3 = async (file) => {
const params = {
Bucket: 'your-s3-bucket',
Key: `videos/${file.name}`,
Body: file,
ContentType: 'video/mp4',
};
try {
const uploadResult = await s3.upload(params).promise();
console.log('Video uploaded to S3:', uploadResult);
return uploadResult.Location;
} catch (err) {
console.error('Error uploading video:', err);
}
};Explanation:
- AWS: Imports the AWS SDK, allowing interaction with AWS services like S3.
- s3: Creates an instance of the AWS S3 service client for managing objects in an S3 bucket.
- s3.upload(params).promise(): Uploads the video file to S3 and returns a promise for the upload result.
- uploadResult.Location: Logs the URL of the uploaded video in S3 after the upload is successful.
- try/catch: Handles any errors that occur during the upload process and logs them to the console.

