Using mongodb in Angular SSR

Discussão em 'Angular' iniciado por DNRN, Abril 8, 2025.

  1. DNRN

    DNRN Guest

    I'm migrating code to a new Angular 19 project using hybrid rendering (SSR + client-side). When rendering on the server, I want to query MongoDB directly instead of using an API. However, I'm encountering issues setting up MongoDB, possibly related to whatwg-url.

    Problem

    When initializing MongoClient, I get a TypeError: Cannot convert undefined or null to object originating from whatwg-url. This happens both with a remote and local database.

    Code

    const mongoClient = new MongoClient(
    config.CONNECTION_STRING,
    {
    tls: true,
    tlsCAFile: join(process.cwd(), 'files', config.TLS_FILE),
    }
    );
    const client = await mongoClient.connect();
    return client.db();


    Error

    TypeError: Cannot convert undefined or null to object
    at Function.getPrototypeOf (<anonymous>)
    at node_modules/whatwg-url/lib/utils.js (.../mongodb.js:20203:41)
    ... (full stack trace in original question)


    What I've Tried

    1. Followed suggestions from this similar issue Angular 17 SSR [vite] Error when evaluating SSR module (updating whatwg-url).
    2. Verified the connection string is correct (error persists even with a local DB).
    3. Tested with both Angulars Express server and as an Angular service -- same error.

    Suspected Cause

    The whatwg-url dependency (used by MongoDB) seems to fail during SSR module evaluation. Is there a known compatibility issue or workaround for Angular 19 + Vite + MongoDB?

    Continue reading...

Compartilhe esta Página