Introduction to Pages in Next.js
In Next.js, every file inside the `pages/` folder automatically becomes a route. This is called **file-based routing**. You don’t need to manually configure a router like in React.
Creating Pages
Let’s create a few pages inside your project:
1. Go to your project folder.
2. Inside `pages/`, create two new files: `about.js` and `contact.js`
3. Add this code to `about.js`:
export default function About() {
return <h1>About Page</h1>
}
And in `contact.js`:
export default function Contact() {
return <h1>Contact Page</h1>
}
Accessing Routes
Once you save those files and run `npm run dev`, you can open:
– http://localhost:3000/about
– http://localhost:3000/contact
This is the beauty of Next.js routing — every page is a file.
Nested Routes (Folders)
You can create folders inside `pages/` to make nested routes.
Example:
pages/blog/index.js → http://localhost:3000/blog
pages/blog/post1.js → http://localhost:3000/blog/post1
Linking Between Pages
Use the built-in `Link` component from `next/link` for client-side navigation:
import Link from 'next/link'
export default function Home() {
return (
<div>
<h1>Home</h1>
<Link href="/about">Go to About</Link>
</div>
)
}
Dynamic Routes
Dynamic routes allow you to create pages based on parameters (like blog posts).
Example:
Create a file: `pages/blog/[slug].js`
export default function BlogPost({ params }) {
return <h1>Post: {params.slug}</h1>
}
When you visit `/blog/hello-world`, it will render that page with `slug = hello-world`.
Catch-All Routes
If you want to match multiple segments, use `[…param].js`.
Example: `pages/docs/[…slug].js` can match `/docs/a`, `/docs/a/b`, `/docs/a/b/c`.
404 Page
You can create a custom 404 page by adding `pages/404.js`. Next.js will automatically use it when a route is not found.
Summary
In this part, you learned:
– How file-based routing works
– How to create static and dynamic routes
– How to link between pages
– How to add custom 404 pages
This routing system is what makes Next.js simple and powerful.
