Next JS Pages
In Next.js, pages are the building blocks of the application's routing and user interface. The pages in Next.js are defined in the pages
directory, and each file in that directory automatically becomes a route. Here’s a detailed look at how pages work in Next.js:
1. The pages
Directory
- The
pages
directory is a special folder that Next.js uses to create routes automatically. - Each file or subdirectory in
pages
becomes a URL accessible in the application. - Example structure:
my-next-app/ └── pages/ ├── index.js // Root page - accessible at / ├── about.js // Accessible at /about ├── contact.js // Accessible at /contact └── blog/ ├── index.js // Accessible at /blog └── [id].js // Dynamic route accessible at /blog/:id
2. Default Pages (index.js
)
index.js
is treated as the default or root file of a directory.- Example:
pages/index.js
is accessible at/
.pages/blog/index.js
is accessible at/blog
.
3. Static Pages
- A static page is created by simply exporting a React component.
- Example:
// pages/about.js const About = () => { return ( <div> <h1>About Us</h1> <p>This is the about page.</p> </div> ); }; export default About;
- Visiting
/about
in the browser will render this page.
4. Dynamic Pages
- Dynamic pages are defined by using square brackets
[ ]
in the file name. - This is useful for pages that require dynamic data, like user profiles or blog posts.
- Example:
// pages/users/[userId].js import { useRouter } from 'next/router'; const User = () => { const router = useRouter(); const { userId } = router.query; return <h1>User ID: {userId}</h1>; }; export default User;
- The route
/users/1
will render the above component withuserId
equal to1
.
5. Catch-All Routes
- You can create catch-all routes to handle multiple path segments.
- Defined using
[...param]
. - Example:
// pages/docs/[...slug].js import { useRouter } from 'next/router'; const Docs = () => { const router = useRouter(); const { slug } = router.query; return <p>Docs: {slug ? slug.join('/') : "Home"}</p>; }; export default Docs;
/docs/a/b/c
will render theDocs
component withslug
equal to['a', 'b', 'c']
.
6. Nested Pages
- Pages can be nested by placing them inside subdirectories.
- Example:
pages/ └── blog/ ├── index.js // Maps to /blog └── [id].js // Maps to /blog/:id
- This allows you to organize related routes logically in subdirectories.
7. API Pages
- The
pages/api
directory is for defining server-side API routes. - Each file in this directory becomes an API endpoint.
- Example:
// pages/api/hello.js export default function handler(req, res) { res.status(200).json({ message: 'Hello World' }); }
- Accessing
/api/hello
will return a JSON response{ message: 'Hello World' }
.
8. Rendering Methods
Next.js pages can use different rendering methods based on the use case:
- Static Generation (SSG): Pages are generated at build time and served as static files. This is the default behavior.
export async function getStaticProps() { return { props: { data: "Static content" } }; }
- Server-Side Rendering (SSR): Pages are generated on each request at runtime.
export async function getServerSideProps() { return { props: { data: "Server-side content" } }; }
- Client-Side Rendering (CSR): Data is fetched after the page is loaded using hooks like
useEffect
.
9. Head Component for Metadata
- To define metadata (such as the page title or description), Next.js provides a
<Head>
component. - Example:
import Head from 'next/head'; const Home = () => ( <div> <Head> <title>Home Page</title> <meta name="description" content="Welcome to the home page" /> </Head> <h1>Welcome Home</h1> </div> ); export default Home;
Summary
- Pages Directory: Core of routing; each file is a route.
- Static, Dynamic, and Catch-All Pages: Defined based on file names (
index.js
,[param].js
,[...param].js
). - API Pages: Define backend logic in
pages/api
. - Rendering Methods: Choose between SSG, SSR, and CSR for different use cases.
- Metadata: Use
<Head>
for defining page-specific metadata.
Pages in Next.js are easy to define and manage thanks to the file-based routing, making building and maintaining routes straightforward and efficient.