node.jstypescriptazureazure-cosmosdbweb-development-server

node.js API not loading environment variable correctly for azure cosmos mongoDB connection string


I have a microsoft azure database and have an api made with typescript to run on a node.js server, when i tested the api the night before all was working, wake up this morning and i keep getting an error

TypeError: Cannot read properties of undefined (reading 'startsWith')
    at connectionStringHasValidScheme (C:\Users\Jordan\Downloads\Website\auth-api\node_modules\mongodb-connection-string-url\lib\index.js:9:30)
    at new ConnectionString (C:\Users\Jordan\Downloads\Website\auth-api\node_modules\mongodb-connection-string-url\lib\index.js:85:34)
    at parseOptions (C:\Users\Jordan\Downloads\Website\auth-api\node_modules\mongodb\lib\connection_string.js:191:17)
    at new MongoClient (C:\Users\Jordan\Downloads\Website\auth-api\node_modules\mongodb\lib\mongo_client.js:51:63)
    at Object.<anonymous> (C:\Users\Jordan\Downloads\Website\auth-api\dist\server.js:25:16)
    at Module._compile (node:internal/modules/cjs/loader:1358:14)
    at Module._extensions..js (node:internal/modules/cjs/loader:1416:10)
    at Module.load (node:internal/modules/cjs/loader:1208:32)
    at Module._load (node:internal/modules/cjs/loader:1024:12)
    at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:174:12)

This is my first web development project so i may be missing something very simple.

TS file

import express, { Request, Response } from 'express';
import cors from 'cors';
import { MongoClient } from 'mongodb';
import dotenv from 'dotenv';

dotenv.config();

const app = express();
const port = process.env.PORT || 3000;
console.log('COSMOS_DB_URI:', process.env.COSMOS_DB_URI);

app.use(cors());
app.use(express.json());

const client = new MongoClient(process.env.COSMOS_DB_URI!);
client.connect().then(() => {
  const db = client.db('jrfbActivityLogger');
  const usersCollection = db.collection('Usernames');

  app.post('/login', async (req: Request, res: Response) => {
    try {
      const { username } = req.body;
      const user = await usersCollection.findOne({ username });

      if (user) {
        res.status(200).json({ success: true });
      } else {
        res.status(401).json({ success: false, message: 'Authentication failed' });
      }
    } catch (error) {
      console.error('Error:', error);
      res.status(500).json({ success: false, message: 'An error occurred' });
    }
  });

  app.listen(port, () => {
    console.log(`Server is running on port ${port}`);
  });
}).catch((err) => {
  console.error('Failed to connect to database:', err);
});

.env file contents with identifying info removed

COSMOS_DB_URI=mongodb://myDBUsername:mydbpassword@mydb.mongo.cosmos.azure.com:myport/?ssl=true&replicaSet=globaldb&retrywrites=false&maxIdleTimeMS=120000&appName=@mydb@

ts config file

{
    "compilerOptions": {
      "target": "ES6",
      "module": "commonjs",
      "rootDir": "./src",
      "outDir": "./dist",
      "strict": true,
      "esModuleInterop": true
    },
    "include": ["src/**/*.ts"],
    "exclude": ["node_modules"]
  }

tried everything from renaming the env file, putting quotes around my connection script and reinstalling all the node modules and i cant seem to figure out the issue. I can confirm my env file is in my api root directory and the syntax is correct.


Solution

  • The issue was what the application was not executed with --env-file=.env.