DEV Community

loading...

3 Steps To Architect A Express Server

jha profile image Amit jha Updated on ・4 min read

Hey there fellas! I'm back with another interesting article that will help you become a full-stack developer.

Let's get started!

excited


A lot of young developers focus too much on making the code work than on the architecture of the project. However, when you work in large teams with potentially hundreds of people working on the same codebase it becomes important to understand and architect your projects so that it's easier for others to understand and maintain.

So in today's post, I'm going to explain a popular pattern with the help of nodejs express server.

NOTE: I'M ASSUMING YOU KNOW BASIC NODEJS


STEP 1: INSTALL DEPENDENCIES

Start a Nodejs project

npm init -y
Enter fullscreen mode Exit fullscreen mode

The above step is going to create the package.json file that we need for a nodejs project. It stores all our dependencies that we will be installing.

Install nodemon

npm install nodemon --save
Enter fullscreen mode Exit fullscreen mode

We basically need this package because we want the nodejs server to automatically restart when we make any changes while development. We will come back to nodemon in a later step.

Install express

duh

npm install express --save
Enter fullscreen mode Exit fullscreen mode

STEP 2: CREATE FILES AND FOLDERS

In this step, we will create all the skeleton files and folders for the server.

But before that lets modify the package.json file a bit.

Right now package.json looks like this

Alt Text

But we are going to add a script to use nodemon for auto-restart of the server while development.

Alt Text

"dev": "nodemon app.js"
Enter fullscreen mode Exit fullscreen mode

We will create app.json soon which will house the starting scripts of the project.

Now we are ready to start creating files and folders.

app.js

Inside your project create a new file called app.js that will be the starting point for the server.

middleware folder

Create a folder in the project directory called middleware that will contain all the middleware your server is using (like auth).

model folder

create a folder in the project directory called model that will house all the files that will contain all the data models and will act as a point of contact with the database. No other part of the server will directly interact with the server but the files inside the model folder.

view folder

Create a folder in the project directory called view that will contain the business logic. Files inside views will interact with the models to get the data from the server.

controller folder

Create this folder in the project directory and remember that you will have all your route callbacks here.

route folder

Finally, create a route folder in the project directory that will contain all the routes in your server.

another way to go about this is by combining controllers and routes as suggested by Daniel Hillmann in the comments

In the end, the folder structure looks like this:

Alt Text


STEP 3:

Now for the sake of demonstration, we will set up an end to end route that will serve a request.

Let's get right into it!!

First, open app.js and type out (or paste) the code

Alt Text

const express = require("express");

const app = express();

app.use("/", require("./route/index"));

const PORT = 3000;

app.listen(PORT, () => {
    console.log(`listening on port: ${PORT}`) // use ` not '
})
Enter fullscreen mode Exit fullscreen mode

line number 5 will forward all requests to the server to the index.js (we will create it) from where we will make calls to the controller.

Next, let's create the index.js file in route folder

Alt Text

const express = require("express");

const router = express.Router();

_hello = require("../controller/hello");

router.get("/hello", _hello.callback);

module.exports = router;
Enter fullscreen mode Exit fullscreen mode

Line number 7 will call hello.callback for every request that is made to _localhost:3000/hello

Next up, let's create the controller callbacks.

Create a file in controller called hello.js and type out this code:

Alt Text

const helloView = require("../view/helloView");
// import your data model and use it 
// for your business logic
module.exports = {
    callback: (req, res, next) => {
        res.status(200).send("Hello There!");
    }
}
Enter fullscreen mode Exit fullscreen mode

THAT'S IT!

now if you start the server by running the following command

npm run dev
Enter fullscreen mode Exit fullscreen mode

you will be able to make a get request from your browser to localhost:3000/hello and see a message saying Hello There!.

In this post, I showed you how to structure your express server so that it's easier to maintain. If you found this post to be informative please consider following me and subscribing to my newsletter.

https://tinyletter.com/jha

Happy Learning,
Jha

Discussion

pic
Editor guide
Collapse
hilleer profile image
Daniel Hillmann

Thanks for this article!

I fail to understand why one would split up route and controller files? To me it's creating some kind of overhead and increasing complexity.

We tend to use a mix of the two together.

Collapse
jha profile image
Amit jha Author

I like to look at route/index.js as a single source of contact with all the routes. You could have 100s of routes with there own query strings etc and all of it stays in one place and app.js stays clean. Whereas when we combine it with the controllers it becomes hard to track (for me). But ultimately all these patterns are there to make things easier. If combining them works for you and your organization than there is no reason to consider seperating them 🌟

Collapse
hilleer profile image
Daniel Hillmann

Alright, I get your point!

The way we deal with it is, we have a route per "type" or "base path" - e.g. consider an api with /api/foo and /api/bar. Then we could have a folder routes with a file foo.js and bar.js - each with the routes belonging to those, rather than having one single file with all routes that would eventually become very, very long as the api grew.

Thread Thread
jha profile image
Amit jha Author

This makes sense to me now!
I think your suggested way may be better than what I've done in this article. I'll update it.

Thanks for sharing! :)

Thread Thread
hilleer profile image
Daniel Hillmann

Amazing! I have to admit I had no intention or expectation of my comment leading to you editing the initial post. How amazing it is that we can discuss, share and learn from each other!

Thread Thread
jha profile image
Amit jha Author

Indeed! :D