How to set up a Node with Express back-end

Last week I deployed my first MERN stack application to production with Heroku. Here it is live on the web and here is the GitHub repo. It’s a social network app for the philosophy discussion club I founded and run called Bros Philosophy Club. The purpose of the app is to give members in the club a place online free of distractions to share articles and ideas for discussion in between in-person meetings.

Initially, the reason I started the club was to have a systematic way to spend time with my bros that also enjoy discussing big ideas. Now, however, I think there is social value in bringing people of diverse backgrounds together to talk in person as well as online. So over time, I’d like to expand the group and offerings.

Over a series of posts, I’d like to share how I built version 1.0 of this app using the MERN stack. In this post, I’ll share the set up for Express and MongoDB. For the Express back-end, I created a file in the main project directory called server.js and I brought in MongoDB through a file called db.js, which I created in directory called config.

Here’s the db.js file:

const mongoose = require('mongoose');
const config = require('config');
const db = config.get('mongoURI');

const connectDB = async () => {
  try {
    await mongoose.connect(db, {
      useNewUrlParser: true,
      useCreateIndex: true
    });

    console.log('MongoDB connected ...');
  } catch (err) {
    console.error(err.message);
    // Exit process with failure to connect
    process.exit(1);
  }
};

module.exports = connectDB;

In the file above I require Mongoose, which is a library that makes working with MongoDB easier and I bring in the details of my MongoDB database cluster from another file in the config directory. In the server.js file below I import the connectDB function from db.js so that it can be called to fire up the database.

Here is the server.js file:

const sslRedirect = require('heroku-ssl-redirect');
const express = require('express');
const connectDB = require('./config/db');
const path = require('path');

const app = express();

// Connect Database
connectDB();

// Enable SSL redirect
app.use(sslRedirect());

// Init Middleware
app.use(express.json({ extended: false }));

// app.get('/', (req, res) => res.send('API Running'));

// Define Routes
app.use('/api/users', require('./routes/api/users'));
app.use('/api/auth', require('./routes/api/auth'));
app.use('/api/profile', require('./routes/api/profile'));
app.use('/api/sparks', require('./routes/api/sparks'));

// Serve static assets in production
if (process.env.NODE_ENV === 'production') {
  // Set static folder
  app.use(express.static('client/build'));

  app.get('*', (req, res) => {
    res.sendFile(path.resolve(__dirname, 'client', 'build', 'index.html'));
  });
}

const PORT = process.env.PORT || 5000;

app.listen(PORT, () => console.log(`Server started on port ${PORT}`));

A good portion of the code in the file above is about preparing the app for production and enabling SSL. However, you can see how Express is required, middleware initiated, and routes corresponding to the core application models are defined.

Overall, this was very simple to set up and understand compared to other back-end frameworks I’ve used. Within 30 minutes or less, I was able to get Express set up and connecting to the MongoDB cluster. Pretty sweet! If you have questions or want to share your insights, please do so in the comments.

Image credit How to create your first MERN (MongoDB, Express JS, React JS and Node JS) Stack by Sam Barros on Medium.

Show Comments

Get the latest posts delivered right to your inbox.