
Basic Routing with the Pages Directory
One of the most fundamental aspects of any web application is its ability to navigate between different pages or views. In Next.js, this is elegantly handled through the pages directory. By default, Next.js uses a file-system-based router. This means that any file inside the pages directory automatically becomes a route in your application. Let's explore how this works.
At its core, the pages directory is where you'll define your application's routes. Each React component file within this directory corresponds to a specific URL path. This convention simplifies development significantly, as you don't need to manually configure routes in a separate file.
app/
└── pages/
├── _app.js
├── index.js
└── about.jsIn the structure above:
pages/index.js: This file will be accessible at the root of your application (e.g.,/).pages/about.js: This file will be accessible at the/aboutpath.
Let's look at a simple example. Create a file named pages/index.js with the following content:
function HomePage() {
return <h1>Welcome to my Next.js App!</h1>;
}Now, create a file named pages/about.js with this content:
function AboutPage() {
return <h1>About Us</h1>;
}