Next.js Pages Router
The Next.js Pages Router allows you to define routes for your
application using the file system. Each file inside the
pages directory becomes a route in your application.
Here's how you can use the Pages Router effectively:
Basic Routing:
- Create Pages:
-
Inside the
pagesdirectory, create.js,.jsx,.ts, or.tsxfiles to define your routes. -
For example,
pages/index.jsdefines the route/, andpages/about.jsdefines the route/about. - Nested Routes:
-
You can create nested routes by creating subdirectories inside the
pagesdirectory. -
For example,
pages/products/index.jsdefines the route/products, andpages/products/[id].jsdefines dynamic route parameters. - Dynamic Routes:
-
Use square brackets (
[]) in the file name to define dynamic routes with parameters. -
For example,
pages/posts/[id].jsdefines a dynamic route with the parameterid.
Linking Between Pages:
import Link from "next/link";
function MyComponent() {
return (
<div>
{/* Navigate to the /about page */}
<Link href="/about">
<a>About</a>
</Link>
{/* Navigate to the /products page */}
<Link href="/products">
<a>Products</a>
</Link>
{/* Navigate to a dynamic route with parameter */}
<Link href="/posts/[id]" as="/posts/123">
<a>Post 123</a>
</Link>
</div>
);
}
Accessing Router Information:
-
useRouterHook: -
Use the
useRouterhook fromnext/routerto access information about the current route. - You can get query parameters, route parameters, and more using this hook.
import { useRouter } from "next/router";
function MyComponent() {
const router = useRouter();
// Get query parameters
const { query } = router;
// Get route parameters
const { id } = router.query;
return (
<div>
{/* Display route parameter */}
<p>Post ID: {id}</p>
</div>
);
}
Customizing Routes:
- Customizing Route Behavior:
-
You can customize route behavior using
getStaticProps,getStaticPaths,getServerSideProps, andgetInitialProps. - These functions allow you to fetch data at build time, server-side, or client-side and pass it as props to your components.
Redirects and Rewrites:
- Redirects:
-
Use the
redirectsproperty innext.config.jsto define redirects. -
For example,
{ "source": "/old-page", "destination": "/new-page", "permanent": true }redirects/old-pageto/new-pagepermanently. - Rewrites:
-
Use the
rewritesproperty innext.config.jsto define rewrites. -
For example,
{ "source": "/blog/:slug", "destination": "/posts/:slug" }rewrites/blog/abcto/posts/abc.
Conclusion:
The Next.js Pages Router simplifies routing by using the file system
as the routing mechanism. You can create nested, dynamic, and custom
routes easily and navigate between them using the
Link component. Additionally, you can access router
information using the useRouter hook and customize route
behavior using special functions like getStaticProps and
getServerSideProps.