How can i deploy a Next.js app with Mongodb to heroku?

I’ve been trying to deploy my Next.js application with mongoDb to heroku platform with no luck. it builds successfully without any errors but for some reasons my app does not work. I checked my heroku logs, and i found this error message.

2020-08-17T21:09:10.846691+00:00 app[web.1]: FetchError: request to http://localhost:3000/api/notes/favicon.ico failed, reason: connect ECONNREFUSED 127.0.0.1:3000

The homepage gets displayed and i can navigate to different routes. but the data that is supposed to be coming from mongoDb is not being displayed. i cannot perform any CRUD operation. I get a 500 internal server error on the homepage and also in the console.

I researched a lot about this issue but i haven’t been able to come up with a solution. Here’s where i’m making a connection to my mongoDb. i have also added my config Vars in the heroku GUI.

import mongoose from 'mongoose'

const connection = {}

const dbConnect = async () => {
if (connection.isConnected) {
  return
} 
 const db = await mongoose.connect(process.env.MONGO_URI, {
   dbName: process.env.DB_NAME,
   user: process.env.DB_USER,
   pass: process.env.DB_PASS,
   useNewUrlParser: true,
   useUnifiedTopology: true
 })

 connection.isConnected = db.connections[0].readyState
 console.log(connection.isConnected, 'Db connected')
}

export default dbConnect

Please what am i doing wrong??

Did you set the Environment Variables for the Database in Heroku’s Access Variables ? Also, If you are using MongoDB Atlas, you will have to whitelist the IP Address. You can either allow all connections or whitelist specific IP Addresses only. Also, the error message that you are getting isn’t anything critical, it’s just because of there is no Icon to display in the Tab Bar.

Hey Muhammad,

nice to meet you! :wave:

  1. If would check if this is a heroku error or an application error by deploying it somewhere else, e.g. vercel.
  2. Have you searched the NextJS Github issues yet? https://github.com/vercel/next.js/issues?q=mongodb
1 Like

Hello, Thank you for your response. Yes i did all of that. The heroku logs isn’t pointing me to any specific thing that i’m doing wrong. Routing works well. I just can’t seem to access my dB