Did someone say routes? Routing is a crucial aspect of web development that allows users to navigate through websites with ease. And it has become smooth like butter with the Next.js 13's new app
directory.
In this blog post, we'll explore the basics of routing in the Next.js 13 app directory and learn how to create dynamic and nested routes.
A small glimpse of the app directory
Next.js 13 app
directory works around folders that come with support for nested routing, layouts, loading states, error handling and more. So you can easily define routes using folders, and UI using various files (with .js/.ts/.jsx/.tsx
extension):
page: provides UI for this route
layout: provides layout UI for this particular route and all descendants
error: provides UI for dealing with errors for this route, unless handled by another error route
loading: provides loading UI for this route
...and more. You can read about it here.
Routing basics
Suppose you're building a blog website, and wish to have a /blog
route. Follow these 2 easy steps to create a route:
Add a new folder named
blog
inside theapp
directory.Inside the
blog
folder, add a page(.js/.ts/.jsx/.tsx
) file to provide the UI for theblog
route.voila, your
/blog
route is created.🎉
Nested Routes
What if you need a route like: /blog/nextjs
? In Next.js 13, you can think of nested routes as folders inside folders. For this:
- create
nextjs
folder insideblog
folder, which is inside yourapp
. And don't forget to addpage
file inside thenextjs
folder. That's it, it's that easy!
Dynamic Routing
What if you don't know the exact routes? Do they depend on some dynamic data? Say you need a route /blog/some-blogID
where this blogID is unique for every blog. You can easily generate a route by:
first, create a folder
blog
inside yourapp
directory.now, create a new folder with square brackets like
[blogID]
inside yourblog
folder. You can give it any meaningful name, but don't forget those square brackets.finally, add
page
file inside your[blogID]
folder. Your route/blog/[blogID]
is created.
To display content for the dynamic route
To display suitable content in your page
file corresponding to the route, you can use the params
argument:
export default function blogID({ params, searchParams }) {
return <div>ID: {params.blogID}</div>
//after params, specify the name you used for your [folder]
}
That's it for now, if you have any questions, feel free to reach out to me. I'll be happy to help. Thanks for reading!⚡