Next.js Discord

Discord Forum

what this error is for? i am new to next.js

Unanswered
Red wood ant posted this in #help-forum
Open in Discord
Red wood antOP
⨯ ReferenceError: document is not defined
at webpack_require (/workspaces/animeTV/.next/server/webpack-runtime.js:33:42)
at eval (./src/app/ui/videoplayer.js:10:62)
at (ssr)/./src/app/ui/videoplayer.js (/workspaces/animeTV/.next/server/app/play/page.js:161:1)
at Object.webpack_require [as require] (/workspaces/animeTV/.next/server/webpack-runtime.js:33:42)
digest: "2858988413"

123 Replies

2 options if you wanna access something on the DOM using SSR, either use a hook library if you don't wanna implement it yourself, or you write the logic yourself. The logic itself is pretty simple, you just need to wait for the component to mount and the DOM to become available. You would use a useEffect with empty dependency array to achieve this.
So something like:

useEffect(()=>{
  ...
  const xxx = document.xxx
  ...
},[])
Red wood antOP
import { notFound } from 'next/navigation';
import dynamic from 'next/dynamic';
const VideoPlayer = dynamic(() => import('@/app/ui/videoplayer.js'), {
  ssr: false, 
});
export default function Page({ searchParams }) {
    const { url = '' } = searchParams;

    if (!url) {
        notFound(); // Redirect to the 404 page if the URL is not found
    }

    return (
        <div>
            <VideoPlayer url={url} />
        </div>
    );
}


using dynamic also showing the error
⨯ ReferenceError: document is not defined
at webpack_require (/workspaces/animeTV/.next/server/webpack-runtime.js:33:42)
at eval (./src/app/ui/videoplayer.js:10:62)
at (ssr)/./src/app/ui/videoplayer.js (/workspaces/animeTV/.next/server/app/play/page.js:161:1)
at Object.webpack_require [as require] (/workspaces/animeTV/.next/server/webpack-runtime.js:33:42)
digest: "2279535291"
GET /play?url=https://play.anonymous.m3u8 500 in 126ms
The problem seems to be in the VideoPlayer component, not the Page
Red wood antOP
//VideoPlayer.js
'use client';
import React, { useEffect, useRef, useState } from 'react';
import Hls from 'hls.js';
import Plyr from 'plyr';
import 'plyr/dist/plyr.css';

const VideoPlayer = ({ url }) => {
  const videoRef = useRef(null);
  const [player, setPlayer] = useState(null);

  useEffect(() => {
    if (!url) return;

    const video = videoRef.current;
    const defaultOptions = {};
    
    const initializePlayer = (source) => {
      if (!Hls.isSupported()) {
        video.src = source;
        const plyr = new Plyr(video, defaultOptions);
        setPlayer(plyr);
      } else {
        const hls = new Hls();
        hls.loadSource(source);
        hls.attachMedia(video);

        hls.on(Hls.Events.MANIFEST_PARSED, function (event, data) {
          const availableQualities = hls.levels.map((l) => l.height);
          availableQualities.unshift(0);

          defaultOptions.quality = {
            default: 0,
            options: availableQualities,
            forced: true,
            onChange: (e) => updateQuality(e),
          };

          defaultOptions.i18n = {
            qualityLabel: {
              0: 'Auto',
            },
          };

          const plyr = new Plyr(video, defaultOptions);
          setPlayer(plyr);
        });

        window.hls = hls;
      }
    };

    const updateQuality = (newQuality) => {
      if (newQuality === 0) {
        window.hls.currentLevel = -1;
      } else {
        window.hls.levels.forEach((level, levelIndex) => {
          if (level.height === newQuality) {
            console.log("Found quality match with " + newQuality);
            window.hls.currentLevel = levelIndex;
          }
        });
      }
    };

    initializePlayer(url);

    return () => {
      if (player) {
        player.destroy();
      }
      if (window.hls) {
        window.hls.destroy();
      }
    };
  }, [url]);

  return <video ref={videoRef} controls />;
};

export default VideoPlayer;
So the only DOM usage I can see in your code is window. The error is talking about document though, so it's possible one of the libs is using that under the hood. My recommendation would be to comment out the useEffect, see if it dismisses the error, and keep slowly uncommenting until you find the exact portion that's causing the error. Since you're already importing it dynamically with ssr off, you shouldn't even have to deal with this so I would also advise to try deleting your .next folder and re-running in the off-chance that it's just an issue there.
Red wood antOP
i ran it. still the same error
after all useeffect code is commented out
the error is same
Weird ask, but can you comment out the component usage and rerun it? Ensure it is that component giving the issue
Red wood antOP
yes that the VideoPlayer component creating the issue
Hmmm, I think the error may be linked to the imported files then
It's possible those files are immediately running and causing the issue
Do they have a nextjs example/guide on how to use them?
@Maheśvara@Red wood antrisky already linked a guide on how to fix this error: https://nextjs-forum.com/post/1283646800632217660#message-1283647840534663168
Based on his code, he's already followed both suggestions and they're not working
Which I also think is weird
Red wood antOP
and more weird is ! i create a totally different app to reproduce the error. it did not reproduce the error.
the error is only in my main project app
Did you try deleting the .next folder that I suggested?
That sounds like it's an issue there if you can't repro the issue
Red wood antOP
yes each time i tried
how to share codespace in github? i can share it with you so that you can look into the error.
Is it public repo?
Red wood antOP
nope
make it shareable so everyone can look at it and everyone can help you. Not only one person
^
Are you working on this locally or using github workspaces?
Red wood antOP
i am using github workspaces. so should i make it public. may be is should try to create a new workspace and try again?
Aside from making it public, I would advise trying to either clone it locally or use something like google idx and see if you're getting the same issue
just share it.
But, if you can make it public, then do. I do understand if it's a work/prod app tho
At this point just use your component with next/dynamic without ssr and then video player should always be client

https://nextjs-faq.com/browser-api-client-component#using-nextdynamic-with-ssr-false
The problem is that he's getting this issue only in this project but not anywhere else when he tries to repro the problem
So something about his current project is off. Whether it's the cached packages or maybe he's using bun or something (bun behaves funky for me), idk.
@Maheśvara The problem is that he's getting this issue only in this project but not anywhere else when he tries to repro the problem
Oh ok didn't see that part, maybe there is another usage in his code

But kinda dependent of the code lol
Maybe, only way to know for sure is either if he shares the repo or is here to answer every question lol
@Maheśvara So something about his current project is off. Whether it's the cached packages or maybe he's using `bun` or something (bun behaves funky for me), idk.
Bun as package manager shouldn't do anything different

Bun as runtime is uhh mostly but weird edge cases so I don't even tho I'm huge fan
@riský Bun as package manager shouldn't do anything different Bun as runtime is uhh mostly but weird edge cases so I don't even tho I'm huge fan
Nah, when I tried to use it as a package manager, it wasn't downloading all the packages at times
It's pretty hit and miss, for now I stick with pnpm
@Maheśvara Nah, when I tried to use it as a package manager, it wasn't downloading all the packages at times
When was that? Because huge fixes in windows and in general recently
(I'm not core team but I am pretty active in their server and usage myself and haven't seen anything for a while)
Anyway getting sidetracked lol
Oh ok if you are in workspace maybe you could get weirdness (but even that I believe is ok for general)
I try it out every 2 months or so lol. I for sure like it as a package manager because it's pretty quick, however for some reason it just doesn't seem to link stuff properly. I can't remember which project (there's a lot I work on both in work and personal) where when I ran the install and then I tried to import a file from the package, it wasn't finding it. Looked into the node_modules and realized it didn't even download it. When I tried it with pnpm it worked as expected. I dev on WSL, maybe that's the issue idk
Red wood antOP
javascript reeeeeeeeeeeeeeeeeeee
Sorry, that was instictive
@Red wood ant https://github.com/immodded/animeTV
where is the error?
@Maheśvara javascript reeeeeeeeeeeeeeeeeeee
Red wood antOP
:lolsob: python programmer hates typescript
It works
Just played an episode
Red wood antOP
just navigate to any anime and play any episode. the stream page hase available streams section you can tap on any category the error will genrated in terminal. the error also genrate with stream server is changed
I get a 404 when I change servers
Red wood antOP
just use gogocdn and vidstreaming
Both play just fine for me
How to repro it?
Maybe all was needed was to effectively clear .next folder cache
He said he already did that
I'm wondering if it's an issue with the workspace itself
Maybe he just needs to start up a new one?
Red wood antOP
i create a new one too its creating the same error
I just saw the error appear, however I wasn't doing anything in the sandbox
Red wood antOP
yes that the errror
https://github.com/immodded/nextjs-errors/tree/main/app

this app is not creating this error. i have make the same code though
Ok, so the error only occurs when I click the stream links below
Red wood antOP
yes sometime it occures when i change server, right now only gogocdn and vidstreaming is up
Yeah, I see it, when I refreshed the /streaming path, it also occured
btw i think you should use the react version instead of directly using https://github.com/chintan9/plyr-react
but if you want to directly use, import the script with inline script maybe and then use window.x
Interesting thing of note is that the error isn't immediately occuring. For some reason it works as expected for a bit before the error pops up, at least for me
Red wood antOP
using plyr-react also causing the same error
idk what's going on, but when I cloned it and installed with pnpm, I'm having no issues rn
I'm using pnpm dev --turbo
this is on google idx as well
also, lmao, i just realized this trash manhua I read years ago has an anime
While testing your site
Can you try installing with pnpm @Red wood ant ? Using pnpm isn't a good solution, I'm just curious if that's the reason I'm not getting the error on my end
Red wood antOP
well is this error can produce any vurnability?
Not sure, gonna retry with an npm install real quick just to verify
immediately got the error with npm
I found the source of the issue at the very least
It's the Plyr import
Red wood antOP
how to solve it?
When I comment out the import the error goes away
Well the immediate solution is using pnpm, but aside from that I'm a bit unsure. Have you checked their github issues to see any reports on this?
You need to import Plyr dynamically
Also use the plyr-react lib
Red wood antOP
okay let me see
Yeah, it works fine now
steps to solve:
1) npm install plyr-react
2) replace:
import Plyr from 'plyr'
with
import dynamic from 'next/dynamic'
const Plyr = dynamic(() => import("plyr-react"), { ssr: false });
That should do the trick
I also removed the dynamic import on VideoPlayer and it works fine
Red wood antOP
i replaced css also with plyr-react/plyr.css


the plyr code is not working
:thinq:
I am still importing the css like import 'plyr/dist/plyr.css';
Since plyr-react is just a react wrapper around plyr
Red wood antOP
is the player working with quality controls and the buttons have its css?
I'm not seeing any quality controls directly on the video player, it looks like a vanilla video player on my end
Red wood antOP
that means plyr is not working.
@Maheśvara also, lmao, i just realized this trash manhua I read years ago has an anime
Red wood antOP
look this blue button. thats working css
Ok, so that's the old version, not plyr-react
Red wood antOP
you got the solution?
@Maheśvara So something like: ts useEffect(()=>{ ... const xxx = document.xxx ... },[])
Chub mackerel
I had similar problem with "window", and this logic save my life
@Red wood ant you got the solution?
So far, if I want the styling, I need to import from the plyr package directly without dynamic import
If I want to get rid of the error, use dynamic import or pnpm
Red wood antOP
but the functionalities of plyr for quality control is not working. do you know about any source or code repo for a player that will have functionality of quality controls and cc too with seek for these m3u8 stream links
the prod.server is not producing this error.
From what I've read, this issue seems to specifically be a dev issue
Also, from what I can see, the styling only works with the direct import from 'plyr'
'plyr-react' doesn't get styled no matter direct or dynamic
And 'plyr' doesn't get styled when dynamic
So basically the way you had it from the very beginning:
import 'plyr/dist/plyr.css'
import Plyr from 'plyr';
Personally, I would look for other libs that won't throw errors and have more documentation.
However if you wanna stick with plyr, that's what you gotta do
Red wood antOP
error was in plyr module. this issue has been resolved! thank all for guidance!