I have angular v18 ssr when trying to connect to mongodb it gives errors about " whatwg-url"

how to solve that error

`` db.ts`


const client = new MongoClient(uri,{
  serverApi: {
    version: ServerApiVersion.v1,
    strict: true,
    deprecationErrors: true,
}
});


export const onlyClient  = async()=>{
  return await client
}

please help!

Hi @Shady_Babloo_gamer,

To gain a better understanding of the issue, could you please share the server file from where the error is occurring?

Meanwhile, looking at the error, it seems like there is a parsing issue as the data being received is undefined/null.

Best,
Kushagra

import { APP_BASE_HREF } from '@angular/common';
import { CommonEngine } from '@angular/ssr';
import express from 'express';
import { fileURLToPath } from 'node:url';
import { dirname, join, resolve } from 'node:path';
import bootstrap from './src/main.server';
import cookieParser from 'cookie-parser';
import { wss } from './backend/web/websocket';
// routes

import {router as loginRouter} from './backend/routes/login';

import {  onlyClient } from './backend/db/mongo-db';

// The Express app is exported so that it can be used by serverless Functions.
export function app(): express.Express {
  const server = express();
  const serverDistFolder = dirname(fileURLToPath(import.meta.url));
  const browserDistFolder = resolve(serverDistFolder, '../browser');
  const indexHtml = join(serverDistFolder, 'index.server.html');

  const commonEngine = new CommonEngine();

  server.set('view engine', 'html');
  server.set('views', browserDistFolder);
  server.use(express.json())
  server.use(express.urlencoded({extended: true}))
  server.use(cookieParser())
  
  server.get('*.*', express.static(browserDistFolder, {
    maxAge: '1y'
  }));


  server.use(loginRouter)

  server.post('/data_log',(req,res,next)=>{
    console.log(req.body)
    res.end()
  })
  // All regular routes use the Angular engine
  server.get('*', (req, res, next) => {
    const { protocol, originalUrl, baseUrl, headers } = req;

    commonEngine
      .render({
        bootstrap,
        documentFilePath: indexHtml,
        url: `${protocol}://${headers.host}${originalUrl}`,
        publicPath: browserDistFolder,
        providers: [
          { provide: APP_BASE_HREF, useValue: baseUrl },
          { provide: 'REQ', useValue: 'hello from serversss' }
        ],
      })
      .then((html) => res.send(html))
      .catch((err) => next(err));
  });

  return server;
}

function run() {
  // const port = process.env['PORT'] || 8080;
  const server =  app();  
  const wsServer = server.listen(8080,async () => { 
    console.log(`Node Express server listening on port 8080`);
    const dbConnect = await  onlyClient() // from db.ts file
    const data = await dbConnect.db('games').collection('singleGame').find(); 
    console.log(await data.toArray())
  });
  wsServer.on('upgrade', (request, socket, head) => {
    wss.handleUpgrade(request, socket, head, (ws) => {
      wss.emit('connection', ws, request);
    });
  });
}

run();

  • i did the exact setup with express only and it did work
  • i think it might be mongodb driver issue with angular setup or angular issue with mongodb
  • error disappear when removing the code related to mongodb connection
  • i use angular ng build command and node server.mjs

@Kushagra_Kesav update 2
i managed to solve the issue related to whtwg-url package by the help the of chatgpt
first i located the error in node_modules>whatwg-url/liv>lib>utils.js
the error comes from this line of code

const AsyncIteratorPrototype = Object.getPrototypeOf(Object.getPrototypeOf(async function* () {}).prototype);

it gives undefined for some reason
chatgpt code

let AsyncIteratorPrototype;

try {
    // Check if async generator functions are supported
    const asyncGenFunction = async function* () {};
    // Verify that the async generator function has a prototype
    if (asyncGenFunction.prototype) {
        // Access AsyncIteratorPrototype
        AsyncIteratorPrototype = Object.getPrototypeOf(Object.getPrototypeOf(asyncGenFunction.prototype));
    } else {
        throw new Error('Async generators are not supported in this environment.');
    }
} catch (error) {
    console.error('Failed to assign AsyncIteratorPrototype:', error);
    // Provide a fallback or handle the error as needed
    AsyncIteratorPrototype = null; // Assigning null as a fallback
}

and it solved the issue
here chatgpt full chat/response
chatgpt response
i omitted export {AsyncIteratorPrototype} because its used locally in same file

please inform whatwp-url devs to modify the package
note => after changing the code in utils file and tested it in normal express mongodb only env. and it works as well

1 Like

edit : node_modules>whatwg-url>lib>utils.js

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.