1. Routing Overview
Routing in Next.js is handled through the pages directory. Each file inside pages represents a route. For example, pages/index.js corresponds to the root route ("/").2. Dynamic Routes
Dynamic routes allow you to create pages with URLs that depend on external data. Simply create a file inside pages directory with square brackets ([]) to denote dynamic segments. For instance, pages/posts/[id].js can match /posts/1, /posts/2, etc.// pages/posts/[id].js import { useRouter } from 'next/router'; const Post = () => { const router = useRouter(); const { id } = router.query; return <div>Post: {id}</div>; }; export default Post;
3. Catch-all Segments
Catch-all routes are denoted by using three dots (...) in the file name within the pages directory. This feature allows you to match any route that hasn't been matched by other pages.// pages/blog/[...slug].js const Blog = () => { return <div>Blog</div>; }; export default Blog;
4. Accessing Query String Parameters
You can access query string parameters using the useRouter hook provided by Next.js.// pages/search.js import { useRouter } from 'next/router'; const Search = () => { const router = useRouter(); const { q } = router.query; return <div>Search results for: {q}</div>; }; export default Search;
5. Layouts
Next.js allows you to create layout components that wrap around your pages for consistent UI elements across your application.// components/Layout.js const Layout = ({ children }) => { return ( <div> <header>Header</header> {children} <footer>Footer</footer> </div> ); }; export default Layout;
6. Navigation
Next.js provides the Link component for client-side navigation between pages.import Link from 'next/link'; const Navbar = () => { return ( <nav> <Link href="/">Home</Link> <Link href="/about">About</Link> </nav> ); };
7. Programmatic Navigation
You can perform programmatic navigation using the useRouter hook or the next/router module.import { useRouter } from 'next/router'; const Home = () => { const router = useRouter(); const handleClick = () => { router.push('/about'); }; return <button onClick={handleClick}>Go to About</button>; };
8. Showing Loading UIs
Next.js automatically adds a loading indicator when navigating between pages using the Link component.9. Handling Not Found Errors
Next.js handles 404 errors by rendering a custom 404 page. You can create a 404.js file inside pages directory to customize the 404 page.10. Handling Unexpected Errors
For handling unexpected errors, you can use custom error pages. Simply create 404.js and 500.js files inside the pages directory for 404 and 500 errors respectively.Routing in Next.js is intuitive and powerful, making it an excellent choice for building modern web applications. Whether you're handling dynamic routes, accessing query parameters, or implementing custom error handling, Next.js provides the tools you need for seamless navigation and user experience.