My Express application folder structure and setup for fullstack projects
WebDevZTH
Posted on August 10, 2021
So far I've been using Nodejs and Express in the back-end for all my full stack projects. I saw a lot of repositories and developers code to get an understanding of what a good folder structure should look like.
Why bother with folder structure?
Its all about the structure, it makes code maintainable and we can easily pin-point bugs, when they arise in the code base. It makes it easy for contributors to help grow the code base efficiently.
A quick breakdown of the folders and files.
At the root of the project we have a configuration
folder that houses the config.js
file and we can access the .env
file by using dotenv
package, safely and securely without compromising security of sensitive data like the database url, hashing secret and other keys that are critical to the development of our application.
require("dotenv").config();
const config = {
env: process.env.NODE_ENV || "development",
port: process.env.PORT || 3001,
mongoUri: process.env.MONGODB_URI,
jwtSecret: process.env.JWT_SECRET || "YOUR_SECRET_KEY",
braintreeId: process.env.BRAINTREE_MERCHANT_ID,
braintreePublicKey: process.env.BRAINTREE_PUBLIC_KEY,
braintreePrivateKey: process.env.BRAINTREE_PRIVATE_KEY,
};
module.exports = config;
Next, we can come to the MVC architecture of the application. The Model-View-Controller is at the heart of the application, the views are handled in the client folder with React.
Models are where we define our database Schema or the structure of the way we want to store specific data into our database, In this project I have used MongoDB for the databse, it is a collection of documents and each document is an instance of the model we define.
Controllers are the way we interact with the database to create, read, update, delete data to and from the database. All of the logic of how our server processes incoming requests and responds to users requests is handled by the controllers.
Finally, Routes folder houses all the endpoints that we expose to query data and send information to the server, it contains different controller logic as middleware to sanitise and ensure that requests to the server are processed in the correct order.
What is Model-View-Controller?
This is a design pattern that is commonly used for web-applications and is one of the most popular design patterns. The View part in a MERN (Mongo, Express, React and Node) application is handled in the front-end by React library. The express based backend which is running in Node is where we have the Controllers, Routes and Models.
Try using this approach in your next project, please share other interesting design patterns for full-stack web development projects ^_^
Posted on August 10, 2021
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.