DEV Community

LG
LG

Posted on • Edited on

1

MERN CRUD on HEROKU #102 – simply & easy !

NOTE : This article assumes you are already into MERN stack;
beginners may subscribe and come back later then ready to deploy their MERN stack.


Consider a project structure :

├─Project-root (current working directory, cwd)
├───/server/... (React as View)
├───/client/... (Express + MongoDB as Control + Model respectively)
└───.vscode, etc. (optional)
Enter fullscreen mode Exit fullscreen mode

Steps to follow :

1) Considering the Project-root or any name of choice as our cwd we currently opened our terminal on at running the following :

cd client && npm run build
Enter fullscreen mode Exit fullscreen mode

2) Copy-paste /build(built) file from /client to /server on your GUI

3) NOTE : Currently we are in the /server : add the following code to your index.js :

const main = async () => {
// (*)
// other .use() mounts 
app.use(express.static(path.join(__dirname, 'build')));
// ...
app.get('/your-get-route-to-match-axios-call-in-React', async (req, res)=>{

    try{
    /*
       Assuming you are already opened client for db. at (*) position (see above)
       const client = await MongoClient.connect(your_MongoDB_connectionURL);
       const db = client.db(your_database_name);

    */
        let feedback = await db.collection(your_collection_name).find({}).toArray();
        res.status(200).json(feedback);
    }
    catch(e){
        res.send(`<h1>404</h1>`);
    }
})
}
main()
Enter fullscreen mode Exit fullscreen mode

I also do consider you have package.json in your /server (I will exclude most important parts) :

// ...
  "main": "index.js",
  "scripts": {
    "start": "node ."
  },
// ...
Enter fullscreen mode Exit fullscreen mode

In case for dot (.) followed in front the node command within package.json , it does correspond to the value of "main" (entry) path ;


Last but not least I assume you have optional (not must) of Procfile in your /server directory . I suggested (more precisely – prepared) contents of package.json so Procfile would appear optional (as default) i.e. default value of web for HTTP is :

web: npm start
Enter fullscreen mode Exit fullscreen mode

4) Lastly , deploy your MERN stack via GitHub integration (or CLI if persisted [link to the guide 101]) : once deployed through Heroku dashboard , press the link to see the app rendered ...

Possible issue met :

  • if you see no error for heroku log --tail , but it says Cannot Get / , all it means : you must update environmental variables on Heroku app settings, the one(s) you added to your .env using dotenv npm package or any relevant | (HINT : those should be of your MongoDB database credentials specifically)

References :

Heroku

This site is built on Heroku

Join the ranks of developers at Salesforce, Airbase, DEV, and more who deploy their mission critical applications on Heroku. Sign up today and launch your first app!

Get Started

Top comments (0)