The XAPlayer secure player in Next.js

Add to your site2 min read

Show the XAPlayer secure player from a Next.js server component (App Router), with the API key kept on the server and a fresh token on every visit.

All guides

In Next.js you get the token in a server component, so the API key never reaches the browser. This example uses the App Router.

Before you start#

  1. In your XAPlayer panel, open Settings and create an API key. It is shown only once, so copy it right away.
  2. Under Websites allowed to show your player, add your site’s full address, such as https://academy.example.com. If your site also opens with www, add that too.
  3. Get the course ID: in Settings, pick the course in “Show the player on your website” and the ID is filled into the sample code. It is also the last part of the course page’s address in the panel.
  4. Install the server-only package: npm install server-only
.env.local
# .env.local (never prefix it with NEXT_PUBLIC_)
XAPLAYER_API_KEY=xap_sk_...

The server function and the page#

// lib/xaplayer.ts
import 'server-only';

type Viewer = { id: string; name?: string; phone?: string };

export async function playerUrl(courseId: string, viewer: Viewer): Promise<string> {
  const res = await fetch('https://en.xaplayer.ir/api/v1/embed-tokens', {
    method: 'POST',
    headers: {
      Authorization: `Bearer ${process.env.XAPLAYER_API_KEY}`,
      'Content-Type': 'application/json',
    },
    body: JSON.stringify({ courseId, viewer }),
    cache: 'no-store', // a fresh token for every visit
  });
  if (!res.ok) throw new Error(`XAPlayer ${res.status}`);
  const data: { url: string } = await res.json();
  return data.url;
}

If it doesn’t work#

What you seeCause and fix
The player area is empty or the browser says it refused to connectYour site isn’t in the allowed websites, or www differs. Add the page’s exact address.
401 unauthorizedThe API key is wrong, or you created a new key and the old one stopped working. Copy the key again.
404 not_foundThe course or video ID is wrong or belongs to another account.
400 bad_requestThe body is incomplete: send exactly one of courseId or videoId, and a non-empty viewer.id.
After a few hours the player says the page timed outThe token expired. Get a fresh token every time the page opens, and never cache the player address.

Try XAPlayer free for 14 days, with 10 licenses on us.

Try it free with your own course