Next.js Discord

Discord Forum

Client Component logic is still executed on the server

Unanswered
Black carp posted this in #help-forum
Open in Discord
Black carpOP
I have the following function in in a client component that I defined by adding 'use client'; on the top of the file:

function getFileFromBase64(input: string, fileName: string, type: string) {
  if (typeof window !== undefined) {
    const parts = input.split(',');
    const content = parts.length > 1 ? parts[1] : parts[0];

    const imageContent = window.atob(content);
    const buffer = new ArrayBuffer(imageContent.length);
    const view = new Uint8Array(buffer);

    for (let n = 0; n < imageContent.length; n++) {
      view[n] = imageContent.charCodeAt(n);
    }

    const blob = new Blob([buffer], { type });

    return new File([blob], fileName, { lastModified: new Date().getTime(), type });
  }

  return null;
}


However, it seems like I'm still getting

ReferenceError: window is not defined
    at getFileFromBase64 (./src/app/component.tsx:35:30)
    at GeneralDocumentComponent (./src/app/component.tsx:193:24)
  40 |     const content = parts.length > 1 ? parts[1] : parts[0];
  41 | 
> 42 |     const imageContent = window.atob(content);
     |                         ^
  43 |     const buffer = new ArrayBuffer(imageContent.length);
  44 |     const view = new Uint8Array(buffer);


in my terminal, does this mean that Next iss still trying to execute this logic on the server side?

I'm using Next 13.5.6

4 Replies

Yes, client components are pre-rendered on the server, any logic that isn't inside a client only function like useEffect will also run on the server in order to get the correct HTML output. If you have logic that should only ever run on the client then you need to put it inside a useEffect or other client only function.
This question comes up a lot, some ressources:
- previous thread from a few days ago: https://nextjs-forum.com/post/1168601503695646760
- official doc https://nextjs.org/docs/messages/react-hydration-error#possible-ways-to-fix-it
- my course on "Browser components" (paid but cheap because it's still in progress): https://course.nextjspatterns.com/manage-client-only-code-in-next-js-with-react-browser-components
That's for fixing your issue, but are you sure your architecture is right? This seems a tad complex
but it depends on what you are trying to achieve, those ressource could at least get you a working code