# Mux & Astro

> Add high-performance video to your Astro project using Mux

[Mux](https://www.mux.com?utm_campaign=21819274-Astro\&utm_source=astro-docs) 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](#mux-player), a drop-in component for adding Mux videos in your Astro project, and [Mux Uploader](#mux-uploader) for uploading videos to Mux from your website. These components integrate seamlessly with [Mux Data](https://www.mux.com/docs/guides/data?utm_campaign=21819274-Astro\&utm_source=astro-docs) to track your video engagement and performance.

You can also interact with your content through the [Mux Node SDK](#mux-node-sdk).

Tip

Learn more about features such as embedding, storing, streaming, and customizing video at [Mux’s dedicated page for video in Astro](https://www.mux.com/video-for/astro?utm_campaign=21819274-Astro\&utm_source=astro-docs)!

## Using Mux in Astro

[Section titled “Using Mux in Astro”](#using-mux-in-astro)

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](https://www.mux.com/docs/integrations/mux-node-sdk?utm_campaign=21819274-Astro\&utm_source=astro-docs) supports both Mux Data and the Mux Video API.

## Prerequisites

[Section titled “Prerequisites”](#prerequisites)

* An existing Astro project. Some features may additionally require an adapter installed for [on-demand server rendering](/en/guides/on-demand-rendering/).
* A Mux account. If you don’t have an account, you can [sign up with Mux](https://dashboard.mux.com/login?utm_campaign=21819274-Astro\&utm_source=astro-docs) using the code `ASTRO` to receive a $50 credit.

## Mux Player

[Section titled “Mux Player”](#mux-player)

In Astro, you can use the full-featured [Mux Player](https://www.mux.com/docs/guides/mux-player-web?utm_campaign=21819274-Astro\&utm_source=astro-docs) 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

```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.

### Installation

[Section titled “Installation”](#installation)

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

* npm

  ```shell
  npm install @mux/mux-player-astro
  ```

* pnpm

  ```shell
  pnpm add @mux/mux-player-astro
  ```

* Yarn

  ```shell
  yarn add @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>`)

### Play a video from Mux

[Section titled “Play a video from Mux”](#play-a-video-from-mux)

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`](#retrieve-asset-data).

All other [options to control the Mux web player](https://www.mux.com/docs/guides/player-api-reference/?utm_campaign=21819274-Astro\&utm_source=astro-docs) (e.g. hide or display controls, style elements, disable cookies) are optional:

src/components/StarlightVideo.astro

```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](https://www.mux.com/docs/guides/stream-recordings-of-live-streams#dvr-mode-vs-non-dvr-mode?utm_campaign=21819274-Astro\&utm_source=astro-docs).

```astro
<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.

## Mux video Element

[Section titled “Mux video Element”](#mux-video-element)

The [Mux video element](https://www.mux.com/docs/guides/play-your-videos#mux-video-element?utm_campaign=21819274-Astro\&utm_source=astro-docs) 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](#mux-player).

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

* npm

  ```shell
  npm install @mux/mux-video
  ```

* pnpm

  ```shell
  pnpm add @mux/mux-video
  ```

* Yarn

  ```shell
  yarn add @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`](#retrieve-asset-data).

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

```astro
<script>import '@mux/mux-video'</script>


<mux-video
  playback-id="FOTbeIxKeMPzyhrob722wytaTGI02Y3zbV00NeFQbTbK00"
  metadata-video-title="Starlight by Astro"
  controls
  disable-tracking
></mux-video>
```

## Mux Node SDK

[Section titled “Mux Node SDK”](#mux-node-sdk)

The [Mux Node SDK](https://www.mux.com/docs/integrations/mux-node-sdk?utm_campaign=21819274-Astro\&utm_source=astro-docs) 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](#mux-environment-api-access).

### Installation

[Section titled “Installation”](#installation-1)

Install the Mux Node SDK using your preferred package manager:

* npm

  ```shell
  npm install @mux/mux-node
  ```

* pnpm

  ```shell
  pnpm add @mux/mux-node
  ```

* Yarn

  ```shell
  yarn add @mux/mux-node
  ```

### Mux Environment API access

[Section titled “Mux Environment API access”](#mux-environment-api-access)

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](https://www.mux.com/docs/core/stream-video-files#1-get-an-api-access-token) 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

```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](/en/guides/environment-variables/) in your Astro project, including creating a [type-safe schema](/en/guides/environment-variables/#type-safe-environment-variables) for your Mux credentials.

### Retrieve asset data

[Section titled “Retrieve asset data”](#retrieve-asset-data)

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:

```astro
---
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](https://www.mux.com/docs/api-reference/video/assets?utm_campaign=21819274-Astro\&utm_source=astro-docs).

## Mux Uploader

[Section titled “Mux Uploader”](#mux-uploader)

[Mux Uploader](https://www.mux.com/docs/guides/mux-uploader?utm_campaign=21819274-Astro\&utm_source=astro-docs) 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.

### Installation

[Section titled “Installation”](#installation-2)

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

* npm

  ```shell
  npm install @mux/mux-uploader-astro
  ```

* pnpm

  ```shell
  pnpm add @mux/mux-uploader-astro
  ```

* Yarn

  ```shell
  yarn add @mux/mux-uploader-astro
  ```

### Upload a video to Mux

[Section titled “Upload a video to Mux”](#upload-a-video-to-mux)

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

```astro
---
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>
```

### Customize the uploader

[Section titled “Customize the uploader”](#customize-the-uploader)

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.

```astro
---
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](https://www.mux.com/docs/guides/uploader-web-customize-look-and-feel?utm_campaign=21819274-Astro\&utm_source=astro-docs) for more options.

### Event handling for uploads

[Section titled “Event handling for uploads”](#event-handling-for-uploads)

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](/en/guides/client-side-scripts/). A `MuxUploaderElement` type is also available.

```astro
---
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>
```

## Official Resources

[Section titled “Official Resources”](#official-resources)

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:

* [The official Mux documentation for Astro](https://www.mux.com/docs/integrations/astro?utm_campaign=21819274-Astro\&utm_source=astro-docs)
* [`@mux/mux-player-astro` API reference](https://github.com/muxinc/elements/blob/main/packages/mux-player-astro/README.md)
* [`@mux/mux-uploader-astro` API reference](https://github.com/muxinc/elements/blob/main/packages/mux-uploader-astro/REFERENCE.md)
* [Building a video uploader with Mux and Astro (YouTube)](https://www.youtube.com/watch?v=aaL1k5FsWfE)
* [Astro uploader and player code example (GitHub)](https://github.com/muxinc/examples/tree/main/astro-uploader-and-player)