Ciprian Craciun - FrontEnd Developer

Ciprian Craciun

FrontEnd/Web Developer

Engineering is about making a product better, learning from past mistakes and create a process which is easy for all to understand.

How to structure a node js application

nodejs app structure
nodejs app structure

I’ve started last weekend to build a node js application using also Express framework for a personal project, with every project you can learn new things, so I’m thinking to share a bit the structure that I used for my back-end server.

There are some things you need to clarify before starting a new project with node js and express, and it’s better to start writing a technical doc to have a clear view of what you want to build, but I think the next structure will fit all kind of projects, here are some steps you need:

Steps we cover for a node js application:

Now that we defined all the structures, let’s take it step by step to see what we need to add for each section.

Install basic npm packages

To start with node js you need to run npm init , this will start populating your package.json file with a basic configuration. So for the start, you need:

body-parser – used to parse incoming requests
express node js framework which helps us to routes and request handling
mongoose – used to interact with MongoDB

Create server.js file

After adding basic npm packages to our node js application, we need to start to create our entry point to the server.js file. Here we add a basic configuration for starting our back-end server at http://localhost:5000

const express = require('express');
const bodyParser = require('body-parser');
const mongoose = require("mongoose");
const app = express();
const port = process.env.PORT || 5000;
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.post('/api/world', (req, res) => {
  res.send(
    `I received your POST request. This is what you sent me!`,
  );
});
app.listen(port, () => console.log(`Listening on port ${port}`));

If you test the POST request with the postman you will see that our basic configuration is working. The POST request will be http://localhost:5000/api/world

POST request
POST request

Use a config folder

I’m using this kind of folder for storing configurations. If you are working with MongoDB, in my case because using MLab the folder config is the right place to add the URL link for database connection.

Create controllers

Why adding this folder? The answer would be: to not have too much logic in the route. All the interaction with the database would be in controllers a folder, this is just an opinion, you can add also the logic in routes.

Adding models

Before adding any logic in our controllers we need to create our model, to know what kind of data we want to save in our database, for example, if you start to create a Login/Register flow a basic model for the User would be:

const mongoose = require("mongoose");
const Schema = mongoose.Schema;
//Create Schema for User
const UserSchema = new Schema({
    name: {
        type: String,
        required: true
    },
    email: {
        type: String,
        required: true
    },
    password: {
        type: String,
        required: true
    },
    date: {
        type: Date,
        default: Date.now,
        required: false
    }
})
module.exports = User = mongoose.model("users", UserSchema);

Adding routes

You can define CRUD operations in this folder and then just call the API in the main file server.js. If you decide for example to create the User flow, you can make the logic inside this folder with connection to controllers and then just call the route in server.js:

const users = require("./server/routes/api/users");
app.use("/api/users", users);

‘Util’ or ‘lib’ folder ?

As the title suggest this is where you can add utility functions for your back-end. If I need to create some validations for Login or Register you can define helper functions in this place, maybe you can use the validator in other places.

To summarize, the following structure for a node js application seems to fit any kind of back-end and it’s easy to follow your code in case you need to fix bugs, or even if you want to test your code it’s easy to add some configurations.

nodejs project structure
nodejs project structure

You may be interested in:
https://stefaniq.com/react-native-maps-for-android/
https://stefaniq.com/how-to-use-redux-persist-with-react-native/

The final code can be found here

Sharing is caring!


Leave a Reply

Your email address will not be published. Required fields are marked *