Skip to content

Mux & Astro

Mux is a hosted media service that provides video streaming infrastructure and performance analytics for businesses of all scales.

When you use Mux to store and host your video content, you’ll have access to Astro-native video components for Mux Player, a drop-in component for adding Mux videos in your Astro project, and Mux Uploader for uploading videos to Mux from your website. These components integrate seamlessly with Mux Data to track your video engagement and performance.

You can also interact with your content through the Mux Node SDK.

Mux’s APIs and web components work in Astro to compress and optimize your videos and streams for the web, adapt the quality of your video to network conditions, and integrate additional features like captions, thumbnails, and analytics. The Mux Node SDK supports both Mux Data and the Mux Video API.

  • An existing Astro project. Some features may additionally require an adapter installed for on-demand server rendering.
  • A Mux account. If you don’t have an account, you can sign up with Mux using the code ASTRO to receive a $50 credit.

In Astro, you can use the full-featured Mux Player as a native Astro component for optimized, responsive video playback and live streams.

Mux Player provides a responsive UI based on video player dimensions and stream type, automatic thumbnail previews and poster images, and modern video player capabilities (e.g. fullscreen, picture-in-picture, Chromecast, AirPlay).

src/components/MyMuxVideoPlayer.astro
---
import { MuxPlayer } from "@mux/mux-player-astro";
---
<MuxPlayer
playbackId="DS00Spx1CV902MCtPj5WknGlR102V5HFkDe"
metadata={{ video_title: 'My Astro Video' }}
/>

Mux Player has built-in support for Mux Data analytics, and will automatically show visitor engagement and video quality metrics in your dashboard once your video has views on your deployed site.

Install the Astro version of Mux Player using your preferred package manager:

Terminal window
npm install @mux/mux-player-astro

Mux Player can also be used in your Astro project as:

  • a web component (<mux-player> from @mux/mux-player )
  • a React component (<MuxPlayer /> from @mux/mux-player-react)
  • an HTML web embed (<iframe>)

Import and use the native <MuxPlayer /> Astro component directly in your .astro files like any other Astro component.

You will need the playbackId for your asset, which can be found in your Mux dashboard or retrieved from its ASSET_ID.

All other options to control the Mux web player (e.g. hide or display controls, style elements, disable cookies) are optional:

src/components/StarlightVideo.astro
<MuxPlayer
playbackId="FOTbeIxKeMPzyhrob722wytaTGI02Y3zbV00NeFQbTbK00"
metadata={{
video_title: 'Starlight by Astro',
}}
style={{
display: 'block',
aspectRatio: '16/9',
backgroundColor: '#000',
margin: '1rem 0 2rem',
}}
primaryColor="#f2ec3a"
secondaryColor="#0caa09"
accentColor="#6e1e99"
defaultShowRemainingTime={true}
/>

If your playbackId belongs to a live stream instead of a prerecorded video on demand, then the Mux Player will allow you to further customize the player with options such as whether or not to enable DVR mode.

<MuxPlayer
playbackId="FOTbeIxKeMPzyhrob722wytaTGI02Y3zbV00NeFQbTbK00"
metadata={{
video_title: 'Starlight stream with Astro',
}}
streamType="live:dvr"
/>

Every live stream is recorded and saved on Mux as a video asset for future on-demand playback.

The Mux video element is a drop-in replacement for the HTML5 <video> element that provides browser support for HLS playback, and has Mux Data automatically configured to show visitor and performance metrics. Use this when you do not need or want all the features of Mux Player.

To use the <mux-video> web component, first install mux-video using your preferred package manager:

Terminal window
npm install @mux/mux-video

Then, you can import and render the web component in a <script> tag in your .astro file.

You will need the playback-id for your video asset, which can be found in your Mux dashboard or retrieved from its ASSET_ID.

All attributes for the HTML 5 <video> element (e.g. poster, controls, muted) are available, as well as additional Mux video player controls (e.g. to provide metadata, control the resolution, disable cookies):

src/components/StarlightVideo.astro
<script>import '@mux/mux-video'</script>
<mux-video
playback-id="FOTbeIxKeMPzyhrob722wytaTGI02Y3zbV00NeFQbTbK00"
metadata-video-title="Starlight by Astro"
controls
disable-tracking
></mux-video>

The Mux Node SDK provides authenticated access to the Mux REST API from server-side TypeScript or JavaScript. This allows you to interact with your Mux assets and data in the component script of your .astro files.

While the Mux Player and Mux Video components do not require authentication and can play any publicly accessible video given its playbackId, connecting to your hosted Mux data via the Node SDK requires a Mux API access token.

Install the Mux Node SDK using your preferred package manager:

Terminal window
npm install @mux/mux-node

API tokens are tied to a specific Mux Environment, which is essentially a container for your videos and related data. When you sign up for Mux, an Environment is created for you automatically. If you’ve created additional Environments, make sure you select the correct one before generating your tokens. From there, you can get your ID and SECRET tokens and provide them to the Node SDK. These tokens can be passed into your Astro components as environment variables stored in a .env file.

This will allow you to create an instance of the Mux Node SDK for retrieving information about your videos, creating new assets, accessing metrics and real-time performance, and more:

src/components/StarlightVideo.astro
---
import Mux from "@mux/mux-node";
const mux = new Mux ({
tokenId: import.meta.env.MUX_TOKEN_ID,
tokenSecret: import.meta.env.MUX_TOKEN_SECRET,
})
---
Read more about using environment variables in your Astro project, including creating a type-safe schema for your Mux credentials.

To fetch information about your video to use in your Astro project, provide the video’s ASSET_ID (available in the Mux dashboard) to the retrieve() helper function. This will allow you to pass values to both your Mux components and your HTML template, such as the video’s title or duration:

---
import Mux from "@mux/mux-node";
import { MuxPlayer } from "@mux/mux-player-astro";
const mux = new Mux({
tokenId: import.meta.env.MUX_TOKEN_ID,
tokenSecret: import.meta.env.MUX_TOKEN_SECRET,
})
const ASSET_ID = "E01irAaN8c6dk1010153uC2mzst7RVbAdJJWtHECAHFvDo";
const asset = await mux.video.assets.retrieve(ASSET_ID);
const playbackId = asset.playback_ids?.find((id)=> id.policy=== "public")?.id;
const videoTitle = asset?.meta?.title;
const createdAt = Number(asset?.created_at);
const duration = Number(asset?.duration)
const date = new Date(createdAt * 1000).toDateString()
const time = new Date(Math.round(duration) * 1000).toISOString().substring(14, 19)
---
<h1>My Video Page</h1>
<p>Title: {videoTitle}</p>
<p>Upload Date: {date}</p>
<p>Length: {time}</p>
<MuxPlayer
playbackId={playbackId}
metadata={{video_title: videoTitle}}
/>

See all asset properties in the Mux Asset API documentation.

Mux Uploader is a fully-functional, customizable video upload UI for your Astro website. The native Astro <MuxUpload /> component allows you to build video upload functionality into your web app.

Mux Uploader supports both manual file selection and drag and drop for file uploads, optional pausing and resuming of uploads, and more.

Install the Astro version of Mux Uploader using your preferred package manager:

Terminal window
npm install @mux/mux-uploader-astro

Before uploading a video, make sure you have your Mux API access tokens configured. With those in place, you can use the create() function from the Mux Node SDK to start a new video upload:

---
import Layout from '../../layouts/Layout.astro';
import Mux from "@mux/mux-node";
import { MuxUploader } from "@mux/mux-uploader-astro";
const mux = new Mux({
tokenId: import.meta.env.MUX_TOKEN_ID,
tokenSecret: import.meta.env.MUX_TOKEN_SECRET
});
const upload = await mux.video.uploads.create({
new_asset_settings: {
playback_policy: ['public'],
video_quality: 'basic'
},
cors_origin: '*',
});
---
<Layout title="Upload a video to Mux">
<MuxUploader endpoint={upload.url} />
</Layout>

You can customize the functionality and appearance of the <MuxUploader /> with additional component attributes. In addition to styling your element, this allows you to control options such as the ability to pause a download or set a maximum file size.

---
import { MuxUploader } from '@mux/mux-uploader-astro';
---
<MuxUploader
endpoint="https://my-authenticated-url/storage?your-url-params"
pausable
maxFileSize={1000000000}
chunkSize={8192}
style={{
'--progress-bar-fill-color': '#7e22ce',
'--button-background-color': '#f0f0f0',
}}
/>

See the Mux Uploader customization guide for more options.

Mux Uploader provides a feature-rich, dynamic UI that changes based on the current state of your media upload. The uploader’s behavior responds to both user-driven events (e.g. selecting a file, retrying after an error) and state-driven events (e.g. upload in-progress, upload successfully completed).

You can listen for these events and handle them in your Astro component with client-side scripts. A MuxUploaderElement type is also available.

---
import { MuxUploader } from '@mux/mux-uploader-astro';
---
<MuxUploader
id="my-uploader"
endpoint="https://my-authenticated-url/storage?your-url-params"
pausable
/>
<script>
import type { MuxUploaderElement } from '@mux/mux-uploader-astro';
const uploader = document.getElementById('my-uploader') as MuxUploaderElement;
uploader.addEventListener('uploadstart', (event) => {
console.log('Upload started!', event.detail);
});
uploader.addEventListener('success', (event) => {
console.log('Upload successful!', event.detail);
});
uploader.addEventListener('uploaderror', (event) => {
console.error('Upload error!', event.detail);
});
uploader.addEventListener('progress', (event) => {
console.log('Upload progress: ', event.detail);
});
</script>

For the full API and webhook reference, usage guides, and information about additional topics, such as integrating with a CMS, building custom video workflows, and more, please see:

More hosted media guides

Contribute Community Sponsor