Routing in node.js

How you code routing between different web pages in node.js + express. Example: Home -> about. Can someone explain how does this work? Thanks

I will split my explanation into two, as there are 2 very distinct possibilities of setting up routing between pages for express. The first is for static content, and the second is for more dynamic content. Regardless of approach the general idea is similar to that of how files are located on your computer. The path to the file in your hard drive is more or less the path of the content in the url.

  1. Static files served with express, in which case the actual file-name within some public folder is automatically made available. IE: you have a public folder served with this:

then going to the server locally would result in the url similar to:
localhost:8080/about.html would serve the about page, and localhost:8080/other.hml would serve the “other” page. index.html is “special” in the sense if you just go to localhost:8080 index.html will be shown automatically, you can consider it the “main” file of a folder.
Along with this if you added a folder to the 3 previous files like so:

  - index.html
  - mustang.html

you can “go into” the cards index.html at the route localhost:8080/cars which will show the cars index.html file, and go to localhost:8080/cards/mustang.html to go into the mustang file. The url structure more or less will match with the folder structure on the server.


  1. You serve “dynamic” content using express to render the “html” to the user in a more dynamic fashion. There are loads of possibilities on how to do this, but the main idea is you setup express routes:

// boilerplate express code is not included here

app.get('/', function (req, res) {
  res.send('Hello World!')

// localhost:8080/other
app.get('other', function (req, res) {
  res.send('Hi from other');

// localhost:8080/cars
app.get('cars', function (req, res) {
  res.send('Hi from cars');

Note the file extension is not included here, as there is no “file”, express generates the “file” dynamically. Since you generate the contents dynamically you could return a different “string” of html depending on information found within a database, or some other dynamic origin of data.


If you just want to learn more about express, reading the getting started page is a great place to start to make sure you understand the basics: