When to use “client-side routing” or “server-side routing”?

tl;dr:

  • with server-side routing you download an entire new webpage whenever you click on a link,
  • with client-side routing the webapp downloads, processes and displays new data for you.

Imagine the user clicking on a simple link: <a href="https://stackoverflow.com/hello">Hello!</a>

On a webapp that uses server side routing:

  • The browser detects that the user has clicked on an anchor element.
  • It makes an HTTP GET request to the URL found in the href tag
  • The server processes the request, and sends a new document (usually HTML) as a response.
  • The browser discards the old webpage altogether, and displays the newly downloaded one.

If the webapp uses client side routing:

  • The browser detects that the user has clicked on an anchor element, just like before.
  • A client side code (usually the routing library) catches this event, detects that the URL is not an external link, and then prevents the browser from making the HTTP GET request.
  • The routing library then manually changes the URL displayed in the browser (using the HTML5 history API, or maybe URL hashbangs on older browsers)
  • The routing library then changes the state of the client app. For example, it can change the root React/Angular/etc component according to the route rules.
  • The app (particularly the MVC library, like React) then processes state changes. It renders the new components, and if necessary, it requests new data from the server. But this time the response isn’t necessarily an entire webpage, it may also be “raw” data, in which case the client-side code turns it into HTML elements.

Client-side routing sound more complicated, because it is. But some libraries really make it easy these days.

There are several upsides of client-side routing: you download less data to display new content, you can reuse DOM elements, display loading notifications to user etc. However, webapps that generate the DOM on server side are much easier to crawl (by search engines), thereby making SEO optimization easier. Combining these two approaches is also possible, the excellent Flow Router SSR is a good example for that.

Leave a Comment