How to structure a node js application

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 for all kind of projects, here are some steps you need:

Steps we cover for a node js application:

Now that we defined all the structure, 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 witch help 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 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 postman you will see that our basic configuration is working. The POST request will be http://localhost:5000/api/world

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 config folder 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 to much logic in the route. All the interaction with the database would be in controllers 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 fallowing structure for a node js application seems to fit to any kind of back-end and it’s easy to fallow 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-structure

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

Final code can be found here !

Sharing is caring!


Leave a Reply

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