How to set up Node.js Routing in a separate directory

We all know how important it is to manage our code properly. When a project becomes large, it becomes very tedious to make small changes and find bugs if the code is not managed properly. We need to waste lots of time finding small bugs if we keep large files. So it is preferred that you create and keep small files. Instead of putting everything in one file, create separate files for small modules.

following this pattern, we are going to set up a new Node.js project routing from scratch. In this setup, we will only import one file from routes in the main server file. and all other things will be managed in the routes directory. So without wasting time let\’s start setting up the project.

I\’m going to take examples from my ongoing project series you can watch the video here

For this, I\’m assuming you have a basic understanding of Node.js.

Let\’s create a fresh project and install dependencies, we only need express for this setup.

  1. Create a new directory and cd into it from your terminal.
  2. run >> npm init -y (it will set up npm in the directory and create a package.json file.)
  3. Install dependences using >> npm install express
  4. create a new file on the root directory. It will be the root file of our project. You can name it whatever you want index.js app.js or server.js
  5. Add the code in the screenshot to your file to create server. You can ignore the database file import and instead of running app.listeten inside db.authenticate, you can run it just after line 11.
\"\"

Now we need to create routes directory on the root which we will use to manage our routes.

\"\"

As you can see, we have created routes directory, and in that directory, we have two subdirectories and a index.js file. this is the file we are importing in main server file.

In this index.js file we are separating the routes for admin and api . All the requests coming for /api will be redirected to api the directory and the same for Admin. All requests coming for /admin routes will be redirected to the admin directory. This is the only purpose for our main route file.

In both subdirectories (api, admin) we have created index.js files. These files will handle all the routes that are coming to them. They will either call a function, send a response or redirect the request to subdirectories. We can also create subdirectories inside admin/api directories to handle sub-routes.

Hope you like the post, please comment if you have any queries or suggestions. You can watch full video on youtube to better understand the concept.

You may also like...