Unlock the Power of Dynamic Routing in Next.js
Setting Up Agility with Next.js
To demonstrate dynamic routing and server-side rendering (SSR), we’ll create a simple travel blog using Next.js and a headless content management system (CMS). First, sign up for a CMS account and create a new instance. Then, set up the necessary content and API keys.
Understanding Next.js Routes
Unlike React, Next.js has a built-in routing system that handles all your routes. Any file with a.js,.jsx,.ts, or.tsx extension under the pages
directory becomes a route. You can create dynamic routes using square brackets []
and the spread operator ...
.
pages/users/[username].js // yields a /users/elijah or /users/elonmusk route
Creating Your First Next.js Page
Let’s create a simple About page to demonstrate Next.js routing. Create an about.js
file in the pages
directory and add some basic content:
function About() {
return (
<div>
<h1>About Us</h1>
<p>Welcome to our travel blog!</p>
</div>
);
}
export default About;
Then, create a Header.js
component to navigate between pages:
function Header() {
return (
<nav>
<a href="/about">About</a>
<a href="/posts">Posts</a>
</nav>
);
}
export default Header;
Dynamic Routing in Next.js
Dynamic routing allows you to create multiple pages with similar content structures. For example, a social network can have multiple user profiles with unique data, but the same content structure. Next.js uses square brackets []
to signify a dynamic route.
pages/posts/[slug].js // yields a dynamic route param with the value of traveling-to-new-york
Query Parameters and Dynamic Routing
Query parameters are used to represent query string parameters and dynamic routing parameters. In Next.js, you can access query parameters using the useRouter
Hook.
import { useRouter } from 'next/router';
function Post() {
const router = useRouter();
const { slug } = router.query;
return (
<div>
<h1>{slug}</h1>
</div>
);
}
export default Post;
Imperative Dynamic Routing with Next.js
Next.js provides two ways to navigate across different pages: declarative navigation using the Link
component and imperative navigation using the router.push
method.
import { useRouter } from 'next/router';
function Post() {
const router = useRouter();
const handleClick = () => {
router.push('/posts/traveling-to-new-york');
};
return (
<div>
<button onClick={handleClick}>Go to Post</button>
</div>
);
}
export default Post;
API Routes in Next.js
Next.js has an api
folder that allows you to structure all your server routes. You can create dynamic API routes using square brackets []
and the spread operator ...
.
pages/api/posts/[slug].js // yields an API route that fetches a specific post
Nested Routing with Query Parameters
Nested routing covers both multiple dynamic segments and multiple dynamic routes. You can use query parameters to filter posts and create a more dynamic routing system.
pages/posts/[category]/[slug].js // yields a nested route with category and slug params
Server-Side Rendering (SSR) and Query Parameters
SSR is useful when you have data that changes often. Next.js regenerates the HTML of pages using SSR whenever a request is made to that page.
import { GetServerSideProps } from 'next';
function Post({ slug }) {
return (
<div>
<h1>{slug}</h1>
</div>
);
}
export const getServerSideProps = async ({ query }) => {
const { slug } = query;
// fetch data from API using slug
return {
props: { slug },
};
};
export default Post;
Handling Common Use Cases for Dynamic Routing
In this article, we’ve covered multiple common examples of using dynamic segments and routes. We’ve also explored nested routing and query parameters with SSR. With this knowledge, you’re well-equipped to create a fully functional full-stack web application using Next.js and a headless CMS.