Home > Enterprise >  Deploying Express app to Vercel gives errors
Deploying Express app to Vercel gives errors

Time:01-29

Running the server locally produces no problems, however when I deploy to Vercel I get the following error:

TypeError: Cannot read properties of undefined (reading 'startsWith') at connectionStringHasValidScheme (/var/task/server/node_modules/mongodb-connection-string-url/lib/index.js:9:30) at new ConnectionString (/var/task/server/node_modules/mongodb-connection-string-url/lib/index.js:85:34) at parseOptions (/var/task/server/node_modules/mongodb/lib/connection_string.js:201:17) at new MongoClient (/var/task/server/node_modules/mongodb/lib/mongo_client.js:46:63) at Object.<anonymous> (/var/task/server/db/conn.js:3:16) at Module._compile (node:internal/modules/cjs/loader:1159:14) at Module._extensions..js (node:internal/modules/cjs/loader:1213:10) at Module.load (node:internal/modules/cjs/loader:1037:32) at Module._load (node:internal/modules/cjs/loader:878:12) at Module.require (node:internal/modules/cjs/loader:1061:19)

I'm really not sure what the problem is - I've done a bit of googling but it hasn't produced many results for this issue (at least not that I found).

server.js

const express = require("express");
const app = express();
const cors = require("cors");
const bp = require('body-parser');
require("dotenv").config({ path: "./db/config.env" });
const port = process.env.PORT || 5000;
app.use(cors());
app.use(express.json());
app.use(require("./routes/auth"));
app.use(require("./routes/user"));
const dbo = require("./db/conn");

app.listen(port, () => {
  dbo.connectToServer(function (err) {
    if (err) console.error(err);

  });
  console.log(`Server is running on port: ${port}`);
});

conn.js

const { MongoClient } = require("mongodb");
const Db = process.env.ATLAS_URI;
const client = new MongoClient(Db, {
  useNewUrlParser: true,
  useUnifiedTopology: true,
});
 
var _db;
 
module.exports = {
  connectToServer: function (callback) {
    client.connect(function (err, db) {
      // Verify we got a good "db" object
      if (db)
      {
        _db = db.db("preview");
        console.log("Successfully connected to MongoDB."); 
      }
      return callback(err);
         });
  },
 
  getDb: function () {
    return _db;
  },
};

I tried cutting the code down to a minimal just to figure out what component is causing the bug, unfortunately with no result.

CodePudding user response:

When you deploy your app to Vercel, you also need declare your environment variables in your project settings page.

Go to the Environment Variables page of your Project Settings and define ATLAS_URI value. Note that you need to deploy your project again before new environment variables becomes available.

  • Related