1. Introduction to File-Based Routing Next.js automatically generates routes based on the file structure in the pages directory.
Basic Example:
- A file pages/index.js maps to the / route.
- A file pages/about.js maps to /about. This convention eliminates the need to configure a separate router and ensures that your app structure mirrors its navigation.
2. Dynamic Routes Dynamic routing in Next.js is a powerful feature for creating pages with varying content. You can define dynamic routes by wrapping part of the filename in square brackets.
Example:
- A file pages/post/[id].js will match routes like /post/1 or /post/42.
- Access the dynamic segment via useRouter() or the getServerSideProps/getStaticProps functions.
import { useRouter } from 'next/router';
export default function Post() {
const router = useRouter();
const { id } = router.query;
return <h1>Post ID: {id}</h1>;
}
3. Nested Routes Nested routing is achieved by creating folders within the pages directory.
Example:
- pages/blog/index.js maps to /blog.
- pages/blog/[slug].js maps to /blog/my-article.
4. Catch-All Routes Catch-all routes handle multiple path segments dynamically using [...param].
Example:
- A file pages/docs/[...slug].js matches* /docs, /docs/getting-started*, and /docs/tutorials/basics. To make the route optional, prepend the file name with [...param].js.
5. API Routes Next.js extends routing to API endpoints. Create backend logic within the pages/api directory.
Example:
- A file pages/api/hello.js maps to /api/hello.
export default function handler(req, res) {
res.status(200).json({ message: 'Hello, world!' });
}
6. Client-Side Navigation with next/link and useRouter Next.js optimizes navigation with prefetching. Use next/link for links and useRouter for programmatic navigation.
- Example with next/link:
import Link from 'next/link';
export default function Home() {
return (
<Link href="/about">
<a>Go to About Page</a>
</Link>
);
}
- Example with useRouter:
import { useRouter } from 'next/router';
export default function Home() {
const router = useRouter();
const navigateToAbout = () => {
router.push('/about');
};
return <button onClick={navigateToAbout}>Go to About Page</button>;
}
7. Shallow Routing Shallow routing updates the URL without triggering a page reload or running getServerSideProps or getStaticProps.
router.push('/about?name=John', undefined, { shallow: true });
8. Middleware for Advanced Routing Next.js middleware lets you intercept and modify requests and responses. It can redirect users based on authentication status or serve localized content dynamically.
- Example Middleware (in middleware.js):
import { NextResponse } from 'next/server';
export function middleware(req) {
const url = req.nextUrl.clone();
if (!req.cookies.get('token')) {
url.pathname = '/login';
return NextResponse.redirect(url);
}
}
9. Internationalized Routing Next.js supports internationalized routing out of the box. Configure locales in next.config.js:
module.exports = {
i18n: {
locales: ['en', 'fr', 'es'],
defaultLocale: 'en',
},
};
- URLs like /fr/about serve French content.
10. Dynamic Routing with API Integration Combine dynamic routes with API calls for dynamic content:
export async function getServerSideProps({ params }) {
const res = await fetch(`https://api.example.com/posts/${params.id}`);
const post = await res.json();
return { props: { post } };
}
export default function Post({ post }) {
return <h1>{post.title}</h1>;
}
Conclusion Next.js routing combines simplicity with flexibility, enabling developers to build scalable, dynamic web applications effortlessly. Whether you're creating a static blog, a multi-language site, or a full-stack app, mastering Next.js routing is a crucial step in your development journey.
With features like dynamic routes, API integration, and middleware, Next.js routing empowers developers to build advanced applications while maintaining an intuitive developer experience. Explore these features in your next project and unlock the full potential of Next.js!