Encountering issues while deploying an Express app on Vercel

After successfully running the server locally, I encountered an error upon deploying to Vercel:

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 have tried researching this issue, but I haven't been able to find a solution so far.

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 attempted to isolate the problematic code segment in order to troubleshoot it, but unfortunately, without success.

Answer №1

After deploying your application on Vercel, it is essential to set up your environment variables in the project's settings section.

Visit the Environment Variables section in your Project Settings and input the value for ATLAS_URI. Remember, you will have to redeploy your project for the new environment variables to take effect.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is it possible to retrieve an object through web API querying by specifying the GUID of an object nested within that object

Is there a way to retrieve an object if it contains another specific object within it? The nested object must have the same guid as the parameter provided. Here's what I have so far, which returns object1 based on its guid: [Route("{id:guid}")] ...

How to rename a column in a collection using mongoDB

I am dealing with a schema setup that resembles the following structure: name: value: pattern: XUknown: Within this collection, I have a staggering 2 million documents. Objective - My goal is to change the name of the column XUknown to XString, the ...

Upon launch or deployment, the Firefox add-on SDK will scan for browser key bindings and alert the user if any conflicts are found

Hey fellow internet enthusiasts :) I've been experimenting with an addon SDK and I've run into a problem. I want my addon to display an input box when I press Ctrl + T. The code works fine in my regular Firefox version because I've removed ...

Guide for receiving client messages on the server side (Node.js) with PubNub

How can I implement message communication between clients and servers using PubNub? Is it possible to subscribe to a channel on the server side (Node.js) and listen for messages? I need to utilize PubNub for the following scenario: => There are numer ...

Discover within a two-tiered set of arrays

I am currently working with a document that looks like this: { "_id":ObjectId("5b306824a1eab22e77858c88"), "data":{ "Key":[ [ "1529587723", "KeyIn" ], [ "1529587723", ...

What are the drawbacks of using global variables?

Is There a Performance Impact to Using Global Variables in JavaScript? Why is it bad to make elements global variables in Javascript? The concept of global variables in JavaScript has long been frowned upon, likened to using street slang compared to m ...

What are the pros and cons of using a piped connection for Puppeteer instead of a websocket?

When it comes to connecting Puppeteer to the browser, you have two options: using a websocket (default) or a pipe. puppeteer.launch({ pipe: true }); What distinguishes these approaches? What are the benefits and drawbacks of each method? How do I know wh ...

"Using the map function in Javascript to iterate through an array and then implementing

I am working on a script that involves an array of the alphabet along with two sets of values. The goal is to determine if a given value falls within the range specified by these two values and then print out the corresponding letter from the alphabet. H ...

Pressing a button in Reactjs triggers a state update to a specific value, avoiding any undefined cases

I've encountered an issue with my onClick event implementation on a button. When I try to set the value to 0, the first click returns an "undefined" value. Initially, I had set the state of value to null in the constructor. Handler function code si ...

Creating a unique field for a document within an array using Mongoose Schema

My goal is not to create a unique array element, but rather to ensure that if I have an array of pairs (which are objects), each pair has a distinct value for the code field. Here is how my schema is defined: const redirectSchema = new mongoose.Schema({ ...

How to call a function within a component from another component without encountering the "Cannot read property" error

Having trouble calling a function from one component in another by passing the reference of one to the other. I keep getting a "Cannot read property" error. Below is the code snippet Alert Component import { Component, OnInit, Output } from '@angula ...

Is there a way to access a PHP value within a self-invoked jQuery function?

I have a page that creates n links using a foreach loop: ...some html and php code <?php foreach ($tables as $table):?> ... some elements generated ... <td><a onclick="setPortalId(<?php echo $table['id']?>);$('#file ...

Prevent certain individuals from selecting a checkbox within HTML forms

Currently, I have a form where users need to fill in their information. However, I want certain parts of the form to be preventable based on the level of access the user has. For example, I have successfully implemented a code snippet onfocus='blur() ...

Accurate linking to the interface while retrieving information from a specified URL

Just started with Angular and attempting to assign the returned json data to my interface, but it's not working as expected. Check out the code I'm using below: Stackblitz Json URL ...

Creating dynamic web pages by using JavaScript to generate HTML code that includes PHP elements and conditional

My project includes a significant amount of HTML and CSS with embedded PHP for session-based content, which is essential. I require access to this session information and cannot rely on cookies alone. I have been examining the following question that disc ...

Creating Vue components based on a deeply nested data structure

Is there a way to efficiently utilize a nested object for generating Vue components? My nested object structure is as follows: "api": { "v1": { "groups": { "create": true, "get": true, ...

Having trouble transforming the JSON object into a usable format

Although I'm still getting the hang of JSON, please bear with me if this seems like a rookie mistake. My approach involves sending a query to a local file that performs a cURL operation on an external site's API and returns a JSON object. Due to ...

AngularJS: Issues with data retrieval in parallel in $http get requests within a $.each loop

Attempting to fetch data for multiple IDs is the goal: (Simplified version, aiming to clarify) Controller: var idList = [39,40,41]; $.each(idList, function(key, value){ var dataObject = { type: "test", id: value }; var getData = DataFactor ...

The toggling feature seems to be malfunctioning as the div section fails to display

I'm facing an issue with my Django project while working on a template. I want to toggle the visibility of a div element between hiding and showing, but the function I used isn't working for some reason. I borrowed the function from a different t ...

Angular integration of Jquery UI datapicker with read-only feature

Having trouble using ngReadonly within a directive, my code isn't functioning as expected: app.directive('jqdatepicker', function() { return { restrict: 'A', require : 'ngModel', link : functi ...