Next.js is a popular web development framework based on React. While React itself is a pleasure to work with, Next.js simplifies development even further. One of the simplifications is the way to get the currently active pathname of a URL in Next.js.
What Is a Pathname?
First things first. Pathname is a property of a URL. In simple words, it’s everything that comes after the domain. For example:
-
URL: https://www.directedignorance.com
Pathname:
/
-
URL: https://www.directedignorance.com/about
Pathname:
/about
-
URL: https://www.directedignorance.com/blog/git-tips-and-tricks
Pathname:
/blog/git-tips-and-tricks
You can find a much more thorough treatment of what a pathname is at MDN Web Docs.
In this blog post, the currently active pathname is simply a pathname of a URL that the user has opened. For example, now that you’re reading this blog post, it is /blog/nextjs-current-pathname
.
Why Should I Care About an Active Pathname?
In some cases, we might want to do something based on the currently active route. A very basic example would be to change the color of a text in a navigation bar, as it is done on this very blog. However, we could do something more elaborate with it. Say, show a popup urging a user to perform some action, or perhaps fire an event to increment some business metric.
How to Determine the Currently Active Route?
Next.js makes it very easy. In your component, we only need to add a few lines:
We can extrapolate from this example and do something more complicated. For example, on this blog I have a NavLink
component that simply changes the text color of the currently active navigation menu item:
As you can see, it’s barely 25 lines of code (empty lines included). However, it is sufficient to improve the user experience by showing where they are on the website.
This simplicity is one of the reasons I migrated to Next.js from Hugo. While the latter is great, I never really used it for anything else except for my blog. Thus, every time I needed to do something slightly complicated, I had to learn the Hugo way of doing it. With Next.js, however, I can leverage my existing React and TypeScript knowledge, which makes development much quicker and more intuitive.
Further Reading
usePathname
documentation