Dima Vavilov
Dima Vavilov

Reputation: 21

NextJS (15.1.7): ReferenceError: XMLHttpRequest is not defined

ERROR DESCRIPTION

Hey everyone! There is code snippet of my frontend:

'use client';

import Image from "next/image";

import { doSomething } from "./serveractions/do-something";

export default function Home() {
  const handleClick = async () => {
    await doSomething()
  }

  return (
    <div className="grid grid-rows-[20px_1fr_20px] items-center justify-items-center min-h-screen p-8 pb-20 gap-16 sm:p-20 font-[family-name:var(--font-geist-sans)]">
      <button onClick={handleClick}>Press me</button>
...

Clicking this button calls Server Action function that uses @basisai/remote-zip to list files of ZIP by URL:

'use server';

import { RemoteZipPointer } from "@basisai/remote-zip";

export const doSomething = async() => {
    const url = new URL("https://github.com/unidoc/unipdf/archive/refs/tags/v3.66.0.zip");
    const remoteZip = await new RemoteZipPointer({ url }).populate();
    const files = remoteZip.files(); 

    files.forEach(file => console.log(file.filename));
}

Clicking that button generates server-side error: server-side error client-side error

If i use exactly the same code on clear NodeJS (Bun) project without NextJS, the snippet works as expected and files are printed to the console.

WHAT I DID TO SOLVE THIS

After googling a bit i tried several mentioned solutions that helped someone:

  1. Recreated NextJS project using npm, yarn and pnpm. (nothing changed)
  2. global.XMLHttpRequest = require('xmlhttprequest').XMLHttpRequest; (throws 'TypeError: i.arrayBuffer is not a function' error)
  3. global.XMLHttpRequest = require('xhr2'); (throws 'TypeError: i.arrayBuffer is not a function' error)
  4. global.XMLHttpRequest = require('node-fetch'); (throws 'TypeError: i.arrayBuffer is not a function' error)

Appreciate any anwser how to solve this or how to correctly use server-side libraries with NextJS that use XMLHttpRequest under their hood :)

Upvotes: 2

Views: 84

Answers (1)

Lionel Rowe
Lionel Rowe

Reputation: 5946

import { RemoteZipPointer } from "@basisai/remote-zip";

Unfortunately, the basisai/remote-zip repo is archived, and it looks like the basisai org is defunct too, so you can't create issues/PRs there and it's unlikely they'll release any updates. So your best bet is probably vendoring it and either replacing the cross-fetch dependency with v4.x or removing it entirely. Most (all?) modern JS environments support fetch natively, so you can probably just remove it (and replace calls to new fetch.Headers with new Headers).

Upvotes: 0

Related Questions