Nik Trenchi
Published on

Using Next.js Dynamic Routes for my TIL Section


Welcome to my first ever blog post!1

Even before starting to build this blog, I knew that I wanted a TIL section. I always liked the simplicity of TIL posts, and felt like the informal nature would push me to write more often2.

I debated between just using a TIL tag instead of a separate section, but eventually decided it's enough of it's own thing and started wondering: How can I do this without copying and pasting everything?

I'm using this awesome Next.js blog template, and the layout of the pages folder looks something like this:

└── blog
    ├── [...slug].js
    └── page
        └── [page].js

I'd soon come to learn that the pages folder is special. From the docs3:

When a file is added to the pages directory, it's automatically available as a route.

Even more curious though: What are the js files with the [] brackets in the names? Well, that's what we're here for! These are "Dynamic Routes", and the one with three dots ([...slug].js) is a "Catch All Route".

That means to get a whole new section of the blog without copying a bunch of code, I could simply put brackets around the blog folder, and give it a more appropriate name like section -- leading to:

└── [section]
    ├── [...slug].js
    └── page
        └── [page].js

So, simply by trying to access a URL like /til/post, the handlers would get something like:

    params: {
        section: "til",
        slug: "post"

... and that's what let me share all the code between TIL section and the rest of the blog! 🎉🎉🎉


  1. I originally had this under the new TIL section, but I felt like I should have a post here first 😅

  2. Which is kinda the whole point!

  3. I'm actually really impressed with the Next.js docs, so there's no reason to repeat everything they say there.

    I'm glad I chose this template 😃