Build it better: Next.js Router

Brandon Lange
3 min readSep 23, 2022

--

In this iteration of this series we are going to take a look at the Next.js Router. The router itself works really well and is much like any other programmatic router that you have used, however there is always room for improvement!

Build it better: Next.js router banner

Please note that this is part of a series where I build up my new SASS business Core Supply. In the previous post we took a look at improving the Next.js API Handler. so if you like this kind of real world scenario coding content, then please let me know in the comments and possibly consider following :)

What issues are we trying to solve?

Currently in the app that I am building I make use of two groups to encapsulate my data. First group is an organisation and second group is a workspace. I include both of these fields in my url as dynamic parameters in the form of /[organisation]/[workspace]/some-route.

Where this becomes messy is that every time that I need to go to a new page I need to make use of the router, extract the query parameters and append them to my routes such as the example below.

There are two fundamental problems with this approach. Firstly you need to define your routes on every page like this, which could become very difficult to know what is happening very quickly. And secondly if the url structure changes we will need to go through our entire app to fix these routes.

How can we solve this?

The best way I could find to solve this issue is to create a new custom router hook for each section of our application. This gives us the ability to define a route once and use it in multiple places as well as have better clarity of the requirements of each route. An example can be seen below.

As this is just an example I have included the organisation/workspace logic within this custom router however it can very easily be extracted and shared amongst all the required routers.

Now this may seem like a lot of code but what it is doing is actually pretty simple. We have a path that we are working with, in this case discovery, and we are generating a path prefix in order to prepend all of our routes with the required format.

Now all we need to do is import and use this router and we now have a fully working, centralised routing system. View the Implementation below to compare the difference.

As you can see this is far more maintainable, extendable, and allows for better visibility (in my opinion), than the original version. If you have any recommendations or alternative ways that you like to handle routing in Next.js then please leave a comment and I will be sure to check it out.

Until then, Happy hacking!

--

--

Brandon Lange

Software developer at AboutYou. My main focus is pretty much to build cool stuff 🤟. Follow me if you feel the same way!