Serving a Node.js Express App From a Subfolder — a Routing Lifehack

An easy way to organize routes in an Express app

Oleg Kondrakhanov
Better Programming

--

Photo by Paul IJsendoorn from Pexels

Express is probably the most popular web framework for Node.js, and tons of tutorials and instructions have already been written about it. However, most of them don’t cover the topic I’m going to tell you about.

A standard approach to routing that is seen across various docs looks like this:

Or like this:

So, your routing structure probably looks somewhat similar to the picture below.

This works perfectly in your local development environment. However, there might be a small problem in the real world. An actual catalog for your application on a hosting platform might be something other than the domain root.

For example, let’s say you deploy an application containing the routes above to the yourdomain.com/hello. Now, if you open yourdomain.com/hello in the browser, you probably expect it to show 'Hello World.' But instead, you get a 404 error.

In order to receive the expected greeting, you should have written the route like this:

The same can be said about the router’s subpath. A proper way to receive ‘Hello from foo’ from yourdomain.com/hello/foo would be:

While it’s not hard to rewrite paths in a small application, trying to do it in a large app with lots of routes (especially routes that are poorly structured) can become a nightmare. In addition, what if you want to change a directory later? In that case, starting to rewrite everything all over again is a bad idea.

A better option is to make just one entry point for routing, and make this entry path configurable.

First, create a config.js to store the project-level variables:

Then, you should reorganize routes structure so that the entry or index router includes all other routes. Its own path would be taken from config.js:

Basically, what we did was transform the previous structure to this:

That’s it. Now, if you deploy your application to a subfolder — for example, yourdomain.com/hello— change the config.js to:

Then, all routes would be updated automatically. If an application is deployed straight to yourdomain.com root, just leave baseUrl: '/' as it is.

I hope this lifehack will help you to organize routes in Express app in a better way.

--

--