Before you go, check out these stories!

0
Hackernoon logoHow I Organized my Node.js REST API by@larswaechter

How I Organized my Node.js REST API

Author profile picture

@larswaechterLars Wächter

CS Student | Software Developer

When I started using Node.js for building REST APIs on the server side, I struggled a lot with the same question over and over again:

How should the folder structure look like?

Obviously there’s not a perfect or 100% correct answer to this question but after reading some articles regarding this topic, I found a folder structure that fits my needs quite good. So today I’d like to show you how I structure my REST APIs.

The APIs are mostly component based what makes it much easier to request only the data we really need. For example we have a User component that contains all information about users.

One thing to mention is that I use express.js as web-framework and TypeORM as ORM. Let’s have a look at the structure.

Directory: root

nodejs-api-structure
└───dist
│
└───logs
│
└───node_modules
│
└───src
│
│   README.md
│   ...

This structure is nothing special and shouldn’t be new to you. It’s actually a basic Node.js setup. The interesting part is the

src
folder on which our focus lies.

So what do we have in here?

nodejs-api-structure
└───src
   │
   └───config
   │
   └───api
   │   │
   │   └───components
   │   │
   │   └───middleware
   │   │
   │   │   routes.ts
   │   │   server.ts
   │
   └───services
   │   index.ts

From here on, we’ll always work from the top of the directory down and I explain each one. Let’s start with the

config
directory.

Directory: src/config

nodejs-api-structure
└───src
    │
    └───config
       │   globals.ts
       │   logger.ts
       │   permissions.ts

This directory includes configuration files. This could be for example:

  • global variables
  • logger config
  • ACL permission
  • SMTP config

Directory: src/api/components

nodejs-api-structure
└───src
    │
    └───api
        │
        └───components
            │
            └───article
            │
            └───auth
            │
            └───country
            │
            └───user
            │   index.ts

Here we have the heart of our component based API. Each component consists of its own routes, controller, model and service.

Let’s deep into the user component and take it as example.

Directory: src/api/components/user

nodejs-api-structure
└───src
    │
    └───api
        │
        └───components
            │
            └───user
                │   controller.ts
                │   model.ts
                │   routes.ts
                │   service.ts

As you can see a component consists of the files I mentioned before. Each file represents one class that is exported. Of course, you can add here more component specific stuff like config or test files.

Since I have multiple components and their classes have the same structure most of the time, I also create interfaces that are implemented in the classes. This helps me to keep the components’ structure straight.

controller.ts

The controller class handles incoming requests, validates them and sends the response data back to the client. It uses the service class to interact with the database.

model.ts

The model represents the database model for its component. In my case it’s a TypeORM class. Mostly it’s used by the service class.

routes.ts

Here we define our API endpoints for the corresponding component and assign the controller methods to them. Moreover we can do things like authorization (e.g. JWT), permission validation (e.g. ACL) or add component specific middleware.

service.ts

The service class acts like a wrapper for the database. Here we read and write data to the database. Furthermore, we can implement caching for example.

Directory: src/api/middleware/

nodejs-api-structure
└───src
    │
    └───api
        │
        └───middlewareauth.tscompression.ts

This folder includes all the API’s global middlewares like authentication, compression, request logging etc.

File: src/api/routes.ts

nodejs-api-structure
└───src
    │
    └───api
        │   routes.ts

Here we register all component and middleware routes.

File: src/api/server.ts

nodejs-api-structure
└───src
    │
    └───api
       │   server.ts

Here we declare everything required for our express server:

  • import middlware / component routes
  • error handling

Later on, we can import the server class for unit tests as well.

Directory: src/services/

This directory contains global services we need for sending mails, authorization or helper methods for example.

nodejs-api-structure
└───src
    │
    └───services
        │   auth.ts
        │   helper.ts
        │   mail.ts

auth.ts

Here we setup things like our passport strategies and define authorization methods.

helper.ts

The helper class contains helper methods for hashing, UUIDs and so on.

mail.ts

This service is used for sending mails and rendering their templates.

File: src/index.ts

This is the startup file of our application. It initializes the database connection and starts the express server.

nodejs-api-structure
└───src
    │   index.ts

All together

Last but not least a complete overview of the project structure:

nodejs-api-structure
└───src
    │
    └───config
    │   │   globals.ts
    │   │   logger.ts
    │   │   permissions.ts
    │
    └───api 
    │   │
    │   └───components
    │   │   │
    │   │   └───article
    │   │   │
    │   │   └───user
    │   │       │   controller.ts
    │   │       │   model.ts
    │   │       │   routes.ts
    │   │       │   service.ts
    │   │
    │   └───middleware
    │   │   │   auth.ts
    │   │   │   compression.ts
    │   │
    │   │   routes.ts
    │   │   server.ts
    │
    └───services
    │   index.ts

That’s it! I hope this is a little help for people who struggled with the same question and didn’t know where or how to start. I think there are still many things you can do better or in a more efficient way.

I’m currently working on a side project, where you can see this folder structure (in a small modified way) in action. Check it out.

Previously published at https://medium.com/swlh/how-i-structure-my-node-js-rest-apis-4e8904ccd2fb

Tags

The Noonification banner

Subscribe to get your daily round-up of top tech stories!