Secure video player for React and Next.js
In Next.js, fetch the token in a server component and render the player straight into the page; the API key never reaches the browser.
Why XAPlayer for React and Next.js
Server components
The token is fetched in a Server Component or Route Handler; only the player URL reaches the browser.
server-only
Importing server-only guarantees the API key never ends up in the client bundle.
Any React app
With Vite or Create React App, your backend fetches the token and React just shows the iframe.
User name on the video
The signed-in user’s name becomes the watermark.
Three steps to secure playback
- Put the API key and URL in server environment variables.
- In the lesson page’s server component, after the purchase check, fetch a token.
- Render the player URL in an iframe.
Tutorials and docs
A taste of the code
The full code, where it goes and how to test it are in the tutorial.
import 'server-only';
export default async function Watch({ params }) {
const user = await requireBuyer((await params).id);
const res = await fetch(`${process.env.XAPLAYER_URL}/embed-tokens`, {
method: 'POST',
headers: { Authorization: `Bearer ${process.env.XAPLAYER_API_KEY}`, 'Content-Type': 'application/json' },
body: JSON.stringify({ courseId: COURSE_ID, viewer: { id: user.id, name: user.name } }),
cache: 'no-store',
});
const { url } = await res.json();
return <iframe src={url} allow="fullscreen" style={{ width: '100%', aspectRatio: '16/9', border: 0 }} />;
}
Questions
Yes. Fetch the token in getServerSideProps or an API route.
Send the token request with cache: 'no-store' so each user gets their own.
Yes, as long as the API key is in server environment variables.
Your backend (Node.js, Laravel or Python) fetches the token and the React app shows the URL in an iframe.
Other platforms
Protect your course today
Signing up takes two minutes. 14 days free, with 10 licenses on us.
Start your 14-day free trial