In this comprehensive and detailed guide on Next Js Router, we will discuss various use cases and feature concepts like:
- Simple Routing in Next Js
- Dynamic Routing Handling
- What is Shallow Routing and How to Implement it?
- Using WildCards in Next Js Routing
- How to use Next js Router Push?
- How to Catch All Routes?
- Handling Refresh in Next Js Dynamic Routing
- and much more…
In web applications especially front-end Javascript apps or server-rendered apps like Next js, handling the Routing efficiently is very important.
Even if we are aware of all the advanced techniques of routing, each use-case needs a special implementation out of the options we have.
In this guide, we will explore various techniques of Next js Routing from simple to advanced levels. Step By Step guide implementing those and also the use-cases where you can or should use them.
Let’s get in…
[lwptoc numeration=”none” numerationSuffix=”none”]
1) Setting Up Next.js Application
First of all, let’s create a new Next js application by executing below create-next-app npx
command by providing the app name:
npx create-next-app@11 my-app
Enter into the application directory:
cd my-app
To run the application on the local webserver, execute the following command:
npm run dev
2) How Next js Routing Works
In Next js, routing works on a file-system-based concept. It means that the next js routes are automatically handled by the file structure that we set up in the pages directory.
For example, the pages/about.js will auto setup a /about route in an application.
// pages/about.js
import React from 'react';
function About() {
return (
<div>
<h1>About Page</h1>
<p>This is the about page of our Next.js application.</p>
</div>
);
}
export default About;
3) Creating Next Js API Routes for Services
By using the next.js API Routes. we can easily build the API endpoints in our application. These API routes reside in the pages/api directory.
For example, we create a file pages/api/hello.js that will generate the api endpoint as example.com/api/hello.
// pages/api/hello.js
export default function handler(req, res) {
res.status(200).json({ text: 'Hello' })
}
4) Next.js Dynamic Routing
Next.js dynamic routing helps in setting up the path parameters dynamically. These query parameters help to pass information from one page to another in dynamica data-based applications.
To create a dynamic route, we add the brackets [] in the dynamic part of the path. For example, the pages/posts/[id].js will help to create dynamic route paths with dynamic values of id like /posts/101 or /posts/655 etc.
// pages/posts/[id].js
import { useRouter } from 'next/router'
const Post = () => {
const router = useRouter()
const { id } = router.query
return <p>Post: {id}</p>
}
export default Post
5) Accessing the Next.js Dynamic Router
The next.js dynamic router uses the useRouter
hook to access the router object inside the next.js component.
By accessing the router object, we can easily access the URL path dynamic parameter query values inside the component as shown below:
// pages/post/[id].js
import { useRouter } from 'next/router'
const Post = () => {
const router = useRouter()
const { id } = router.query // 'id' matches the filename '[id].js', so we can destructure it from 'router.query'
return (
<div>
<h1>Post {id}</h1>
<p>This is a detailed view of the post with id: {id}.</p>
</div>
)
}
export default Post
Inside pages/post/[id].js
, we can use the useRouter
hook to access the dynamic part of the URL.
6) Exploring Next.js Router Push
Router push in next js allows and provides the next.js router to programmatically navigate to different pages. For example, we need to navigate a user by redirecting it to a specific page after an action is completed.
By deploying the router.push(…) you can redirect or navigate a user to a specific page in the application.
// SomeComponent.js
import { useRouter } from 'next/router'
const SomeComponent = () => {
const router = useRouter()
const handleButtonClick = () => {
router.push('/other-page')
}
return <button onClick={handleButtonClick}>Go to Other Page</button>
}
7) How to Implement Nested Routes in
Next.js?
The nextjs does not provide any native support to the nested routes or sub-routes/ child routes, but we can achieve a similar behaviour by deploying the dynamic routes.
For example you have a URL route like this /posts/1/comments/2, then you can create a file at pages/posts/[postId]/comments/[commentId].js.
// pages/posts/[postId]/comments/[commentId].js
import { useRouter } from 'next/router'
const Comment = () => {
const router = useRouter()
const { postId, commentId } = router.query
return (
<div>
<h1>Post ID: {postId}</h1>
<h2>Comment ID: {commentId}</h2>
</div>
)
}
export default Comment
You can access routes like /posts/1/comments/2, where 1 is the post ID and 2 is the comment ID.
8) Managing Next.js Router Query Params
For the management of next js router query params, we can use the router object’s query property.
The query property contains an object having all the query parameters.
// pages/posts/[id].js
import { useRouter } from 'next/router'
const Post = () => {
const router = useRouter()
const { id } = router.query
const { comment } = router.query // Accessing the query param 'comment'
return (
<div>
<p>Post: {id}</p>
<p>Comment: {comment}</p>
</div>
)
}
9) Using the Next.js Wildcard Route
The next js wildcard route which is also known as catch-all routes can be used to match routed which do not refer to any file in the pages folder.
// pages/posts/[...slug].js
import { useRouter } from 'next/router'
export default function Post() {
const router = useRouter()
// The slug will be an array of segments. e.g., ['2023', '05', 'my-post-title']
const { slug = [] } = router.query
return (
<div>
<h1>{slug.join('/')}</h1>
{/* Render your post content here */}
</div>
)
}
In above example, slug is an array that contains the dynamic segments of the URL. This array can be used to fetch and render the corresponding post content.
The wildcard route feature in Next js is very flexible and can be used for multiple scenarios for example:
1 – Catch-all routes
In case where we need to catch all the routes which do not correspond to any of the page files, then these wildcard routes can come in handy. For example, a blog can have multiple dynamic slugs that can be handled easily using wildcard routes.
2 – Dynamic URL Slugs
In a blogging platform where each URL can contain dynamic numbers like date, year, and month like myblog.com/2023/05/my-post-title. We can easily fetch these dynamic values from URLs to render the content or fetch related content from databases.
3 – Nested Routes
As we already discussed, Next js does not support natively the nested routing, so by using the wildcard routes we can achieve it as a workaround. For example, the URL/user/:username/posts/:postId we can easily fetch the URL params and use them in our page component accordingly.
10) Understanding Next.js Shallow Routing
The Next.js shallow routing method allows you to change the URL without running the data fetching methods again and again. Shallow Routing in useful for use-cases like pagination and filtering where the same page can have different data for different query parameters.
Let’s understand in more detail how generally it routing works and what Shallow methods makes the difference.
When we navigate from one to a new page by direct link or programmatically using the router.push() the Next.js works as follows:
- It stops the rendering process on the current page.
- Then it fetched the required Javascript code for the new page to be loaded.
- After that, the new page’s data fetching methods like getStaticProps, getServerSideProps or getInitialProps are executed.
- Once the data is fetched, the new page is rendered with data fetched.
With Shallow Routing, Steps 2 and 3 are skipped and URL is changed, but the page component doesn’t rerendered and data fetching methods are not called.
Shallow Routing is useful if we only want to update the URL and not the data on the page.
// SomeComponent.js
import { useRouter } from 'next/router'
const SomeComponent = () => {
const router = useRouter()
const handleButtonClick = () => {
router.push('/same-page?param=newValue', undefined, { shallow: true })
}
return <button onClick={handleButtonClick}>Change Param</button>
}
11) Refresh/Reload Page Programmatically
In tNext.js, we can reload or refresh the page by calling the router.reload() method from the useRouter hook.
This method will reload the current page route, hence will rerender the page and rerun the data fetching methods.
import { useRouter } from 'next/router'
export default function SomeComponent() {
const router = useRouter()
const handleRefresh = () => {
router.reload()
}
return <button onClick={handleRefresh}>Refresh Page</button>
}
Conclusion
In the comprehensive tutorial on Next.js Router and routing techniques, we discovered various methods and use cases to handle routing with examples. We discussed various Next js routing techniques including SimpleRouting, Routing with Whilcard, Dynamic routing, and Shallow routing with detailed examples. Hope this will be helpful.
Leave a Reply