'SvelteKit: 500: Module "stream" has been externalized for browser compatibility

I'm trying to setup a authenticated connection to Firebase using WebKit.

The below code "works" in a sense that I receive the data from Firebase Realtime Database as expected.

index.svelte

<script context="module">
    // import serviceAccount from '../private/my-firebase-private-key.json'
    import { google } from 'googleapis'

    let firebaseAccessToken

    const serviceAccount = {
    "type": "service_account",
    "project_id": "my-test-project-xxxxxx",
    "private_key_id": "0d33XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
    "private_key": "-----BEGIN PRIVATE KEY-----\nXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX-----END PRIVATE KEY-----\n",
    "client_email": "firebase-adminsdk-xxxxx@my-test-project-xxxxxx.iam.gserviceaccount.com",
    "client_id": "9999999999999999999999",
    "auth_uri": "https://accounts.google.com/o/oauth2/auth",
    "token_uri": "https://oauth2.googleapis.com/token",
    "auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
    "client_x509_cert_url": "https://www.googleapis.com/robot/v1/metadata/x509/firebase-adminsdk-xxxxxx%40my-test-project-xxxxxx.iam.gserviceaccount.com"
}


    async function firebaseAuth() {
        let scopes = [
            'https://www.googleapis.com/auth/userinfo.email',
            'https://www.googleapis.com/auth/firebase.database',
        ]

        let jwtClient = new google.auth.JWT(
            serviceAccount.client_email,
            null,
            serviceAccount.private_key,
            scopes
        )

        return new Promise((
            resolve,
            reject
        ) =>
            jwtClient.authorize((error, tokens) => {
                if (error) {
                    console.log('Error making request to generate access token:', error)
                    reject(error)
                } else if (tokens.access_token === null) {
                    console.log(
                        'Provided service account does not have permission to generate access tokens'
                    )
                    reject(error)
                } else {
                    firebaseAccessToken = tokens.access_token
                    resolve(tokens.access_token)
                }
            })
        )
    }

    // export async function load({ page, fetch, session, context }) {
    export async function load({ fetch }) {
        await firebaseAuth()
        // console.log(`firebaseAccessToken: ${firebaseAccessToken}`)
        const res = await fetch(
            'https://myfirebasedatabase.app/jsondb.json',
            {
                headers: { 'Authorization': `Bearer ${firebaseAccessToken}` },
            }
        )
        const data = await res.json()

        if (!res.ok) {
            return {
                status: res.status,
                error: new Error('Could not fetch data'),
            }
        }

        return { props: { myData : data } } <-- DATA is RECEIVED
    }
</script>

<script>
export let myData

onMount(() => {
        console.log(myData) <---------------- NEVER EXECUTED
})
</script>

The problem is that the UI shows the following error ...

500: Module "stream" has been externalized for browser compatibility and cannot be accessed in client code.

... handled by this __error.svelte file

<script context="module">
    export function load({ error, status }) {
        return {
            props: {
                title: `${status}: ${error.message}`
            }
        };
    }
</script>

<script>
    export let title;
</script>

<h1>{title}</h1>

I feel like it has something to do with Vite or another configuration stuff but I have too little experience with svelte to be sure. Did you have this kind of error previously?

Thanks for your help.

Side note: the code codes from NodeJs Authenticate REST Requests Documentation from Google and uses the Google APIs NodeJS Library



Solution 1:[1]

I have the same error only writen only this line of code

 import { google } from 'googleapis'

get the same error 500.


But when add this config for vite server in svelte.config.js file

//svelte.config.js    
vite: {
        optimizeDeps: {
            exclude: ['googleapis']
        }
    }

get this error:

The requested module '/node_modules/googleapis/build/src/index.js?v=9d844668' does not provide an export named 'google'

I've seen in the browser/devtools network option, when i use exclude de size of index.js file is 70 Kb, but when is use include the size is 46 Mb.

I think is purely error of vite server to try load node_modules in webbrowser of client side.

If i found a solution for this error surely share the solution

Regards!.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Geogt