Swiftorial Logo
Home
Swift Lessons
Matchups
CodeSnaps
Tutorials
Career
Resources

Custom Routing in Next.js

1. Introduction

Next.js provides a powerful and flexible routing system based on the file-system structure. Custom routing allows developers to build dynamic and user-friendly URLs that enhance SEO and user experience.

2. Dynamic Routes

Dynamic routes in Next.js are created using square brackets in the file name. For instance, if you want a route that captures user IDs, you name your file [id].js.


        // pages/users/[id].js
        import { useRouter } from 'next/router';

        const User = () => {
            const router = useRouter();
            const { id } = router.query;

            return 

User ID: {id}

; }; export default User;

3. Catch-All Routes

Catch-all routes are useful for matching multiple segments. They are defined using three dots inside square brackets. For example, [...slug].js can capture any path segment.


        // pages/blog/[...slug].js
        import { useRouter } from 'next/router';

        const BlogPost = () => {
            const router = useRouter();
            const { slug } = router.query;

            return 

Blog Post: {slug.join('/')}

; }; export default BlogPost;

4. Nested Routes

For nested routes, you can create a folder structure within the pages directory. For example, a file structure like pages/blog/index.js and pages/blog/[id].js will create routes /blog and /blog/[id].


        // pages/blog/index.js
        const BlogIndex = () => {
            return 

Blog Home

; }; export default BlogIndex;

5. Best Practices

When implementing custom routing, consider the following best practices:

  • Use meaningful and descriptive route names.
  • Keep routes shallow to improve performance.
  • Leverage dynamic routes to reduce the number of static pages.
  • Regularly audit your routing structure for optimization.

6. FAQ

What are the benefits of custom routing?

Custom routing allows for cleaner URLs, better SEO, and enhanced user experience.

Can I use both static and dynamic routes?

Yes, you can mix static and dynamic routes in your Next.js application.

How can I handle 404 pages?

You can create a custom 404.js file in the pages directory to handle 404 errors.