Routing HTTP Requests

Routing HTTP Requests

OG Routing

With a static HTML site (and the first incarnation of my personal website) you had a file structure like this:

mywebsite/
  index.html
  favicon.ico
  2021/
    why-i-like-she-ra.html

And you would run a webserver, or host this somewhere like Netlify that would serve index.html if someone requested /index.html (or / if you configured your website correctly).  and if someone requested /2021/ they might see a directory listing and if they went to /2021/why-i-like-she-ra.html they'd see that page.

This is file based routing and it's very easy to understand, but can be limiting.  If this was my blog, at some point I might have 100s of posts and want to store this data in a database.  I could then write a script that would show the right piece of data based on the URL.

Modern Handlers and Routing

The mechanism of associating a URL input like / or /2021/ or /tag/princesses to an action is called routing.  ExpressJS, NextJS and Flask have good guides on how to route URLs to handlers.  Handlers are bits of code that turn a request into a response.

I've been writing a lot of NextJS, so let's dive into how they do things.  If I want something to show a blog post at /year/slug-of-article (e.g. /2021/adora-and-catra) I would do something like this:

mywebsite/
  pages/
    [year]/
      index.js
      [slug].js

Now if I went to mywebsite.com/2021 that would go to pages/[year]/index.js and 2021 would be an argument to the component in that file.  We would refer to that component as a handler because it handles the request.

If I went to mywebsite.com/2021/the-old-ones-technology it would pass 2021 and the-old-ones-technology to my component in [slug].js and presumably I would find the blog post to serve.

Routing via scripts whether it's NextJS or Flask or a PHP script you put together can end up saving you a lot of time when laying out your pages, but also make your URLs easy to read, consume and even discover.


Got routing questions?  routing@davedash.33mail.com