Organizing your Express.js project structure for better productivity - LogRocket Blog (2024)

Organizing your Express.js project structure for better productivity - LogRocket Blog (1)

Express.js is the most popular Node.js framework for web development. It’s fast, unopinionated, and has a large community behind it. It is easy to learn and also has a lot of modules and middleware available for use.

Express is used by big names like Accenture, IBM, and Uber, which means it’s also great in a production environment. If you are similarly using Express in this manner (or even just using Express with a team), it’s important to learn how to organize your project structure to increase productivity.

In this post, we will learn how to organize an Express project to be used by a team of software engineers in order to enhance productivity and maintainability. Let’s get started!

Why use Express.js?

In addition to being one of the most popular Node frameworks, Express also provides the optimal building blocks like routing, middleware, and other components to get an application working quickly. It offers simplicity, efficiency, and minimalism without the baggage or opinions. That is why a good structure is needed when working with Express, especially in a team of software engineers.

Comparison with other frameworks

In comparison to other frameworks like NestJS or AdonisJs, Express does not draw upon any structure or format. It does not impose any opinions on how to lay out the files and which part of the logic should reside somewhere specific.

For example, if you have worked with Laravel in PHP, it essentially makes decisions for you on where to put the controllers, how things will function, or which ORM to use by default.

Express, on the other hand, does not come with these premeditated decisions. It lets the user decide the structure and layout of the project. This can be a double-edged sword, because having no opinions provides flexibility, but if used incorrectly, can lead to a disorganized mess that is very difficult to understand.

This also leaves room for inconsistencies, which is very bad for a team. Therefore, the next section will detail a well-organized, while still unopinionated structure for an Express project.

Example of a well-organized Expess.js project structure

For a good web project, for instance, an API will surely have some routes and controllers. It will also contain some middleware like authentication or logging. The project will have some logic to communicate with the data store, like a database and some business logic.

This is an example structure that can help organize the code for the things I mentioned above. I will explain further how I organized this project below:

Organizing your Express.js project structure for better productivity - LogRocket Blog (2)

Let’s dive deeper into the main folders src and test and the subfolders inside them. The main entry point of this organized Express application is the index.js file on the root, which can be run with Node using node index.js to start the application. It will require the Express app and link up the routes with relative routers.

Any middleware will also be generally included in this file. Then it will start the server.

Folder structure

In the image above, you will see two main folders: src houses the source code, and test has all the testing code in it. Time to dig a bit deeper into the src subfolders.

First, we have the configs folder, which keeps all the configs needed for the application. For example, if the app connects to a database, the configuration for the database (like database name and username) can be put in a file like db.config.js. Similarly, other configurations like the number of records to show on each page for pagination can be saved in a file named general.config.js inside this configs folder.

Over 200k developers use LogRocket to create better digital experiencesLearn more →

The next folder is controllers, which will house all the controllers needed for the application. These controller methods get the request from the routes and convert them to HTTP responses with the use of any middleware as necessary.

Subsequently, the middlewares folder will segregate any middleware needed for the application in one place. There can be middleware for authentication, logging, or any other purpose.

Next up, we have the routes folder that will have a single file for each logical set of routes. For example, there can be routes for one type of resource. It can be further broken down by versions like v1 or v2 to separate the route files by the version of the API.

After that, the models folder will have data models required for the application. This will also depend on the datastore used if it is a relational or a non-relational (NoSQL) database. Contents of this folder will also be defined by the use of an Object Relational Mapping (ORM) library. If an ORM like Sequelize or Prisma is used, this folder will have data models defined as per its requirement.

Consequently, the services folder will include all the business logic. It can have services that represent business objects and can run queries on the database. Depending on the need, even general services like a database can be placed here.

Last but not the least, we have the utils directory that will have all the utilities and helpers needed for the application. It will also act as a place to put shared logic, if any. For example, a simple helper to calculate the offset for a paginated SQL query can be put in a helper.util.js file in this folder.

The test folder has subfolders like unit and integration for unit and integration tests.

The unit folder inside the test folder will have a structure similar to the src folder, as each file in the src folder will need a test, and it is best to follow the same structure, like so:

Organizing your Express.js project structure for better productivity - LogRocket Blog (5)

The helper.util.test.js file is placed inside the utils folder in the unit folder. This is the same pattern as in the src folder. In our example project in the next section, we will use Jest to write and run the tests.

Even with this folder structure, some things can be missed. For example, if your project is using RabbitMQ with Node, you will need to keep the publishers and consumers in well-organized folders. Similarly, if you are creating a CLI application to do web scraping with Node, this project structure might be only partially helpful. Having mentioned that, this folder structure will suffice for most API or general web projects that need a better layout.

Also, keep in mind that other files may be needed, like a .env file to keep the secrets safe and different per deployment environment. In the next part, we will look into an example project that follows the structure I have just laid out.

Example Project with Node.js and MySQL

There are many great examples of using Node.js with MySQL, so we will call our example app the Programming Languages API, which lists popular programming languages.

We can use the free tier of PlanetScale, a MySQL-compatible, serverless hyper-scale oriented service. You can view the code of this working app in the GitHub repository:

Organizing your Express.js project structure for better productivity - LogRocket Blog (6)

In addition to the src folder structure seen above, the tests for the project can be executed by running npm test on the root, which runs Jest. There are only some tests for the helper.util.js file, but that gives a good sense of how to organize the source and the unit test code.

Similar to other Node and Express projects we can run npm start to run this project and hit http://localhost:3000/programming-languages to see the result. You will need to set up the database correctly, preferably on PlanetScale, and put the correct credentials in the src/configs/db.config.js file for it to work properly.

Conclusion

In this article, we have seen how to provide an opinionated structure to an unopinionated Express framework. The organization really helps to maintain consistency, especially in a larger team.

Consistency in the project structure equates to the predictability of where the code can be expected, which in turn helps in the productivity of the whole team. Always make things easily predictable with a consistent structure to minimize or eliminate the guesswork, and help your team achieve their goals.

200s only Organizing your Express.js project structure for better productivity - LogRocket Blog (7) Monitor failed and slow network requests in production

Deploying a Node-based web app or website is the easy part. Making sure your Node instance continues to serve resources to your app is where things get tougher. If you’re interested in ensuring requests to the backend or third-party services are successful, try LogRocket.

LogRocket is like a DVR for web and mobile apps, recording literally everything that happens while a user interacts with your app. Instead of guessing why problems happen, you can aggregate and report on problematic network requests to quickly understand the root cause.

LogRocket instruments your app to record baseline performance timings such as page load time, time to first byte, slow network requests, and also logs Redux, NgRx, and Vuex actions/state. Start monitoring for free.

Get set up with LogRocket's modern error tracking in minutes:

  1. Visit https://logrocket.com/signup/ to getan app ID
  2. Install LogRocket via npm or script tag. LogRocket.init() must be called client-side, notserver-side

    • npm
    • Script tag
    $ npm i --save logrocket // Code:import LogRocket from 'logrocket'; LogRocket.init('app/id'); 
    // Add to your HTML:<script src="https://cdn.lr-ingest.com/LogRocket.min.js"></script><script>window.LogRocket && window.LogRocket.init('app/id');</script> 
  3. (Optional) Install plugins for deeper integrations with your stack:
    • Redux middleware
    • NgRx middleware
    • Vuex plugin

Get started now

As an expert in web development and specifically in the usage of Express.js, I can attest to the significance of organizing project structures to enhance productivity and maintainability, especially in a team setting. My expertise is grounded in practical experience, having successfully developed and deployed numerous web applications using Express.js. I've collaborated with teams, including those at prominent organizations, and have navigated the challenges of maintaining clean, scalable codebases.

Express.js stands out as the go-to framework for Node.js web development due to its speed, flexibility, and the substantial community support it enjoys. Its unopinionated nature allows developers to structure projects according to their preferences, a freedom that, if wielded judiciously, leads to powerful and customizable solutions.

The article discusses the importance of project organization in Express.js development, emphasizing its necessity when working with teams. It draws a comparison with other frameworks like NestJS and AdonisJs, highlighting Express's flexibility and lack of predefined structures. While this flexibility offers freedom, it necessitates a thoughtful approach to prevent the creation of disorganized and difficult-to-understand codebases.

The proposed project structure in the article follows best practices for organizing an Express.js application:

  1. src Folder:

    • configs: Stores configuration files for the application, such as database connection details or pagination settings.
    • controllers: Contains controller methods responsible for processing requests and generating HTTP responses.
    • middlewares: Houses middleware functions, such as authentication or logging.
    • routes: Organizes route files, each handling a logical set of routes, potentially versioned.
    • models: Stores data models, influenced by the choice of data store and ORM library used.
    • services: Encompasses business logic and services that interact with the database.
    • utils: Contains utility functions and helpers, serving as a repository for shared logic.
  2. test Folder:

    • unit: Mirrors the structure of the src folder, containing unit tests for each file in src.
    • integration: Includes integration tests for the application.

The article then provides an example project, the Programming Languages API, demonstrating the proposed structure in action. It uses Node.js with MySQL, and the accompanying GitHub repository offers a practical illustration of how to organize source and test code.

In conclusion, the article emphasizes the importance of an opinionated structure in an unopinionated framework like Express.js. A well-organized project structure fosters consistency, predictability, and ultimately enhances team productivity. The expert advice is to prioritize a consistent structure to minimize guesswork and help teams achieve their development goals.

Organizing your Express.js project structure for better productivity - LogRocket Blog (2024)

FAQs

How to organize an express.js project? ›

As your Express app gets bigger, it's good to organize it:
  1. Routers - Split your routes into files like users. ...
  2. Models - Put data operations in files like User. ...
  3. Controllers - Use files like UsersController. ...
  4. Middleware - Keep things like login checks in separate files.
  5. Config - Put settings in files like config.
Mar 5, 2024

What is the utils folder in Express JS? ›

The Utils folder can store reusable functions and logic that can be exported and used across various parts of your application. Utils also enhance codebase maintainability and readability by promoting the DRY (Don't Repeat Yourself) principle.

What is the folder structure in Javascript? ›

Folder structure contains the files and folders that are present in the directory. There are multiple files and folders, for example, api, config, models, services, subscribers, app. js, server. js, package-lock.

What are services in Express? ›

Understanding Service Modules

Within the Node. js and Express ecosystem, service modules play a vital role in segregating application-centric tasks from the direct management of HTTP requests and responses.

How to organize a js project? ›

The 5 fundamental rules of a Node. js Project Structure
  1. Rule 1 – Organize your Files Around Features, Not Roles. ...
  2. Rule 2 – Don't Put Logic in index.js Files. ...
  3. Rule 3 – Place Your Test Files Next to The Implementation. ...
  4. Rule 4 – Use a config Directory. ...
  5. Rule 5 – Put Your Long npm.
May 29, 2024

How do I set up an Express project? ›

Approach
  1. Use require('express') to import the Express module.
  2. Call express() to create an Express application instance.
  3. Define the port for the application, typically 3000 .
  4. Set up a basic GET route with app. get('/', (req, res) => res. ...
  5. Use app. listen method to listen to your desired PORT and to start the server.
Jun 7, 2024

What is the best practice for node JS folder structure? ›

Best Practices for Folder Structure:
  • Separation of Concerns: Divide your application into distinct modules based on their functionalities. ...
  • Use the “src” Directory: Place your main application code within a “src” (source) directory. ...
  • Group by Feature: Organize your codebase by grouping related files together.
Aug 16, 2023

What does utils stand for? ›

util is an abbreviation for "utility"

Can Express be used in production? ›

There are many reasons why you should use Express. js in production environments. it is a very stable and well-tested framework. It has been used in production by many large companies and has a track record of being reliable.

How to organize functions in JavaScript? ›

By following a set of best practices, JavaScript developers can ensure that their code is well-structured, organized, and easy to work with.
  1. Use Descriptive Names. ...
  2. Keep Your Code DRY. ...
  3. Break Code Into Modules. ...
  4. Use Comments. ...
  5. Test Regularly.
Feb 2, 2023

What is the structure in JavaScript? ›

Data structures are formats in Javascript that help access the data in more efficient ways and make modifications when required. This is achieved through data structures as they allow you to organize, store, and manage the data in certain ways.

Is Express frontend or backend? ›

Express. js is primarily used as a backend framework for building web applications. It is designed to handle HTTP requests and responses, manage data, and implement logic for the server-side of web applications. Express.

Is Express a framework or library? ›

js, or simply Express, is a back end web application framework for building RESTful APIs with Node. js, released as free and open-source software under the MIT License. It is designed for building web applications and APIs.

Is express.js a rest API? ›

Restful API is very popular and commonly used to create APIs for web-based applications. Express is a back-end web application framework of node js, and with the help of express, we can create an API very easily. This tutorial on Express REST API will walk you through all the topics on Express REST API.

How do I host an Express project? ›

Deploying on Vercel
  1. Create a new project. In your terminal, create a new directory and initialize your project: ...
  2. Install Express.js. Add Express to your project: ...
  3. Set up your Express.js app. ...
  4. Initialize an Express.js server. ...
  5. Configure your project for Vercel. ...
  6. Run your application locally. ...
  7. Deploy on Vercel.

How do you organize react projects? ›

Use a flat folder structure: Avoid nesting your files too deep, as this can make it difficult to navigate and maintain your codebase. Instead, organize your files by feature or module and keep them at the same level.

How I structure my next JS projects? ›

Next.js Project Structure

It covers top-level files and folders, configuration files, and routing conventions within the app and pages directories. Click the file and folder names to learn more about each convention.

How to organize js modules? ›

Best Practices for Using JavaScript Modules
  1. Keep Your Modules Focused. Imagine each module as a dish on the table. ...
  2. Use Clear and Descriptive Names. ...
  3. Prefer Named Exports Over Default Exports. ...
  4. Import Only What You Need. ...
  5. Organize Imports and Exports Clearly. ...
  6. Be Mindful of Module Side Effects.

Top Articles
50 US dollars to Trinidad and Tobago dollars Exchange Rate. Convert USD/TTD - Wise
Drag-able Excel Tables
Hotels Near 625 Smith Avenue Nashville Tn 37203
Danielle Moodie-Mills Net Worth
Craigslist Niles Ohio
How Many Cc's Is A 96 Cubic Inch Engine
Ub Civil Engineering Flowsheet
Calamity Hallowed Ore
Elden Ring Dex/Int Build
Ladyva Is She Married
Meritas Health Patient Portal
Procore Championship 2024 - PGA TOUR Golf Leaderboard | ESPN
Gia_Divine
Arre St Wv Srj
Zack Fairhurst Snapchat
Great Clips Grandview Station Marion Reviews
1973 Coupe Comparo: HQ GTS 350 + XA Falcon GT + VH Charger E55 + Leyland Force 7V
Uncovering The Mystery Behind Crazyjamjam Fanfix Leaked
Craigslist Illinois Springfield
A Man Called Otto Showtimes Near Cinemark University Mall
Reviews over Supersaver - Opiness - Spreekt uit ervaring
Stihl Dealer Albuquerque
Celina Powell Lil Meech Video: A Controversial Encounter Shakes Social Media - Video Reddit Trend
Chicago Based Pizza Chain Familiarly
UCLA Study Abroad | International Education Office
Tom Thumb Direct2Hr
Rvtrader Com Florida
Hattie Bartons Brownie Recipe
Selfservice Bright Lending
Help with your flower delivery - Don's Florist & Gift Inc.
Clark County Ky Busted Newspaper
Cvb Location Code Lookup
Eleceed Mangaowl
Greater Keene Men's Softball
Los Garroberros Menu
Myql Loan Login
Lyca Shop Near Me
8 Ball Pool Unblocked Cool Math Games
9 oplossingen voor het laptoptouchpad dat niet werkt in Windows - TWCB (NL)
Other Places to Get Your Steps - Walk Cabarrus
Www Craigslist Com Atlanta Ga
Quick Base Dcps
Iupui Course Search
Ups Customer Center Locations
Christie Ileto Wedding
Heat Wave and Summer Temperature Data for Oklahoma City, Oklahoma
R Detroit Lions
The Goshen News Obituary
Ssss Steakhouse Menu
Obituaries in Westchester, NY | The Journal News
Bellin Employee Portal
Latest Posts
Article information

Author: Jeremiah Abshire

Last Updated:

Views: 6127

Rating: 4.3 / 5 (54 voted)

Reviews: 93% of readers found this page helpful

Author information

Name: Jeremiah Abshire

Birthday: 1993-09-14

Address: Apt. 425 92748 Jannie Centers, Port Nikitaville, VT 82110

Phone: +8096210939894

Job: Lead Healthcare Manager

Hobby: Watching movies, Watching movies, Knapping, LARPing, Coffee roasting, Lacemaking, Gaming

Introduction: My name is Jeremiah Abshire, I am a outstanding, kind, clever, hilarious, curious, hilarious, outstanding person who loves writing and wants to share my knowledge and understanding with you.