ReferenceError: XMLHttpRequest is not defined on api endpoint

I'm deploying a NextJS project using next on pages. I'm getting a "ReferenceError: XMLHttpRequest is not defined" when trying to run the code block below. It sounds like the worker behind the pages is trying to use XMLHttpRequest instead of the normal fetch? How do i fix this?


async function getSpotifyTokens(
    clientId: string,
    clientSecret: string,
) {
    const tokenUrl = 'https://accounts.spotify.com/api/token'
    const authStr = `${clientId}:${clientSecret}`
    const b64AuthStr = Buffer.from(authStr).toString('base64')

    const headers = {
        Authorization: `Basic ${b64AuthStr}`,
        'Content-Type': 'application/x-www-form-urlencoded',
    }
    // const body = new URLSearchParams({
    //     grant_type: 'client_credentials',
    // })
    const body = 'grant_type=client_credentials'

    const response = await fetch(tokenUrl, {
        method: 'POST',
        headers,
        body,
    })

    if (!response.ok) {
        const errorText = await response.text()
        throw new Error(`Failed to get token: ${response.status} - ${errorText}`)
    }

    const tokens = (await response.json()) as ExtendedGetRefreshedAccessTokenResponse
    return tokens
}


here's the dev branch of my site: https://dev.cf-next-cpa.pages.dev/
The endpoint in question is this:
https://dev.cf-next-cpa.pages.dev/api/spotify_auth/refresh_tokens

-----
The funny thing about this though is that my code has been running perfectly fine before this (for like 400+ commits/deploys) then all of a sudden it stopped working now.

I'm also using supabase but it doesn't seem to be the issue since the error only occurs exactly at the fetch call.

Did something change with CF workers? The code works just fine locally btw ,also i use the pages dir instead of the app dir.
Was this page helpful?