Introduction to File-Based Routing

Next.js simplifies routing by adopting a file-based routing system. This means that the URL structure of your application directly corresponds to the file structure in your project's "pages" directory. Each file you create in the "pages" directory becomes a route in your Next.js application.


Default Routes

By default, Next.js uses the "index.js" file in the "pages" directory to represent the root route. The root route is accessible at /. For example, creating a file named "about.js" in the "pages" directory makes it accessible at /about.


Dynamic Routing

Next.js supports dynamic routing, which allows you to create routes with variable segments. You can use brackets [ ] to indicate dynamic segments in your route files. For example:

<pre>
// pages/post/[id].js
import { useRouter } from 'next/router';
function PostPage() {
const router = useRouter();
const { id } = router.query;
return (
<div>
<h1>Post {id}</h1>
<p>This is a dynamic route for post {id}.</p>
</div>
);
}
export default PostPage;
</pre>

In this example, the value of id is dynamic and can change with different URL segments.


Linking Between Pages

To navigate between pages in Next.js, you can use the Link component. For example:

<pre>
import Link from 'next/link';
<Link href="/about">
<a>About Us</a>
</Link>
</pre>

This code creates a link to the "About Us" page. When users click the link, Next.js handles the client-side navigation without a full page reload.