HeyGen-Official / InteractiveAvatarNextJSDemo

MIT License
92 stars 98 forks source link

Incorrect URL Handling for streaming.proto in Production with Next.js #25

Open mateuszwszola opened 2 months ago

mateuszwszola commented 2 months ago

Hey everyone!

I wanted to share a solution to an issue I've been wrestling with for a while. If you're using the @heygen/streaming-avatar with Next.js (v14) in production, this might save you some headaches!

The Problem I've encountered: In the deployed version of the application, the avatar wasn't loading because the URL for streaming.proto was getting messed up. Instead of https://static.heygen.ai/static/streaming.proto, it was trying to load it from https://my-app-name.app/static.heygen.ai/static/streaming.proto.

The Fix: I solved it with a simple Next.js middleware. Here's the code:

// middleware.js in the root of the project
import { NextResponse } from "next/server";

export function middleware(request) {
  const { pathname } = request.nextUrl;

  if (pathname.startsWith("/static.heygen.ai/")) {
    const dynamicPath = pathname.replace("/static.heygen.ai", "");
    const externalUrl = `https://static.heygen.ai${dynamicPath}`;

    return NextResponse.redirect(externalUrl);
  }

  return NextResponse.next();
}

This middleware intercepts requests starting with /static.heygen.ai/ and redirects them to the correct external URL, solving the misformatted URL issue.

Hope this helps someone out there! Let me know if it works for you, and if you have any feedback.

Happy coding! 🚀

teereximus88 commented 1 month ago

You. Are. The. MAN!!!

I'd been banging my head against the wall trying to get the mic input to work and this solved it. The HeyGen folks should take note of this as I believe the issue is likely causing downstream pain for a lot of others. Big thanks for sharing 🙏.

Ryanklass commented 1 month ago

Thanks for this! been looking for a solution for a while now