Next.js Discord

Discord Forum

Express MongoDB serverless function will not connect to MongoDB, even though locally it works fine{

Unanswered
Chausie posted this in #help-forum
Open in Discord
ChausieOP
I am using a vercel serverless function to connect my front end vite application to my MongoDB. And when I run the code locally everything works fine but as soon as I deploy on vercel it says my serverless function has crashed

my vercel.json is:
{
    "version": 2,
    "builds": [
      {
        "src": "index.js",
        "use": "@now/node"
      }
    ],
    "routes": [
      {
        "src": "/(.*)",
        "dest": "index.js"
      }
    ]
  }

my code is
const express = require('express');
const { MongoClient } = require('mongodb');
const dotenv = require('dotenv');
const app = express();
const PORT = 3000; // You can change the port number if needed
dotenv.config();
let mongouri = process.env.MONGODB_URI;

// Allow CORS
app.use((req, res, next) => {
  res.header('Access-Control-Allow-Origin', '*');
  next();
});

// Middleware to parse JSON request body
app.use(express.json());

// Check if mongodb_uri exists in environment variables if not throw error
if (!mongouri) {
  throw new Error('MONGODB_URI missing from .env');
} else {
  console.log('MONGODB_URI is: ', mongouri);
}

// Connect to the MongoDB database using MongoClient
MongoClient.connect(mongouri, { useUnifiedTopology: true })
  .then(client => {
    console.log('Connected to MongoDB');
    const db = client.db(); // Get the database instance

    // Create a Mongoose schema for the 'music' collection
    const musicSchema = {
      title: String,
      artist: String,
      link: String,
      image: String,
      id: String,
    };

    // Route handler for '/songs' GET request
    app.get('/songs', async (req, res) => {
      try {
        // Retrieve all items from the 'music' collection
        const songs = await db.collection('music').find().toArray();
        res.json(songs); // Send the retrieved items as JSON response
      } catch (err) {
        console.error(err);
        res.status(500).json({ error: 'Internal Server Error' });
      }
    });

    // Register hello world route
    app.get('/', (req, res) => {
      res.send('Hello World!');
    });

    // Start the server
    app.listen(PORT, () => {
      console.log(`Server is running on http://localhost:${PORT}`);
    });
  })
  .catch(err => {
    console.error('Error connecting to MongoDB:', err);
    process.exit(1);
  });

module.exports = app;

My ENV variables are set up properly on vercel's side, it just crashes when I even try to hit the / route. Been at this for 2 days and its driving me crazy and help would be appreciated

0 Replies