DEV Community

Christian
Christian

Posted on

How to eliminate dead links in your Next.js app

At my company, Proper, we like pages. Like...a lot! Our platform is a fairly large Next.js application consisting of ~70 pages. And we link between pages ~200 places in the application.

We find that having pages make features easily discoverable by end-users and developers alike. And having pages (urls) for each of our features help us maintain a sane information architecture throughout our platform.

The Next.js file-system based router help us stay consistent and organised around our pages. But we've had some incidents where our application was released with dead links.

At one point, a file in the /pages folder was renamed and we simply overlooked (forgot to change) some of the links to that page. Another time, a bit of "clever" string concatenation caused an issue. In this case, we had moved a page, and failed to update all links to the page correctly due to the concatenated links.

next-type-safe-routes to the rescue

To mitigate this issue, I created next-type-safe-routes. A small Next.js plugin accompanied by a couple of utility methods.

next-type-safe-routes parses the /pages folder in your Next.js app and generates types for all the pages and API routes in the application. These types can then be used to ensure that you only link to pages (and only use API routes) that actually exists in your application.

With the types generated, we can use the getRoute utility to retrieve a link that is guaranteed to exist in the application:

import { getRoute } from 'next-type-safe-routes';

getRoute("/users"); // for simple routes
getRoute({ route: "/users/[userId]", userId: "1" }); // for dynamic routes
Enter fullscreen mode Exit fullscreen mode

And with a tiny abstraction on top of the next/router and next/link, our routing developer experience now looks something like this:

Alt text of image

As an added benefit, we also get type-safe API routes!

Having type-safety for all our links gives us confidence when refactoring as well as a top notch developer experience with auto-completed routes. I'm hoping this library might help others who face the same challenges we did 🙂

https://github.com/ckastbjerg/next-type-safe-routes

Top comments (0)