Introduction

There are many different ways how I can implement routing in my application. In this article I will show some of the possibilities.


Link

The link component is the prefect element for routing, by default it handles already a lot of things, that will improve the user experience a lot. For implementing it, all I need to do is to create the element:

<Button asChild variant={"outline"}>
    <Link href={`/project/${project.id}`}>View details</Link>
</Button>

Each Link needs a href that defines the path it should route to, in this case the route is [[πŸ“œ AppRouter#Dynamic Routes [ ]|dynamic]]. In order for this to work, I need to add this file:

src/app/project/[projectId]/page.tsx

Access Route Param

For extracting the route param, I should make sure the name of the [dynamic folder] and the variable within my component have matching names

src/app/project/[projectId]/page.tsx
type ProjectDetailProps = {
  params: {
    projectId: string;
  };
};
 
const ProjectDetailPage = async ({ params }: ProjectDetailProps) => {
  const { projectId } = await params;
  
  // add data fetching
  
return (...)

Once the param got accessed, I can easily fetch the element via data fetching


Typed Route & path.ts

When adding for every link component manually a href, it’s just a matter of time until I make a mistake. Or I might need to change a path and will end up having to change the same href in x-amount of places. Since thats obviously not a sustainable approach, I should always implement Typed Routes and a dedicated path.ts file wich contains all possible paths in one place.

src/path.ts

For setting this up, I need to make a change to the next.config.ts file

const nextConfig: NextConfig = {
  typedRoutes: true, /* add this line */
};

Then I just need to define the paths within my path.ts file

import type { Route } from "next"; // import required
 
// example one simple route
export const ticketsPath = (): Route => "/tickets";
 
// example two route with dynamic param
export const ticketPath = (ticketId: string): Route =>
  `/tickets/${ticketId}` as Route;

And in my Link element, I can the just call the defined route

// import { ticketPath } from "@/paths";
<Link href={ticketPath(ticket.id)}View</Link>

Here I linked a mini documentation about Typed Routes of Next.js


Conclusion

Routing is definitely one of the most important features of a website, I’m looking forward to explore more ways of routing and improving transitions even further - I will definitely have to come back and expand this article.