Tag: Module 2: Pages and Routing

  • Module 2: Pages and Routing

    Lesson 1: Dynamic Routing

    Dynamic routing in Next.js allows you to create pages that adapt to different data inputs. This is achieved using square bracket syntax for dynamic segments in the pages/ directory. For example:

    • File Structure:

    pages/post/[id].js

    • Accessing Dynamic Parameters: Use the useRouter hook or server-side methods like getStaticProps or getServerSideProps to retrieve dynamic values:

    import { useRouter } from ‘next/router’;
    export default function Post() { const router = useRouter(); const { id } = router.query;

    return

    Post ID: {id}

    ;
    }

    Lesson 2: API Routes

    API routes allow you to create serverless backend functionality directly within your Next.js application. These are created inside the pages/api/ directory. Example:

    •  File Structure:

    pages/api/hello.js

    • Sample API Route:

    export default function handler(req, res)
    { res.status(200).json({ message: ‘Hello, API!’ });
    }

    • Usage: Call the API route from the frontend using fetch :

    fetch(‘/api/hello’)
    .then((res) => res.json())
    .then((data) => console.log(data));

    Lesson 3: Catch-All and Nested Routes

    Catch-all routes allow you to capture multiple dynamic segments in a single route. Use square brackets with an ellipsis (… ) for this purpose.

    •  File Structure:

    pages/post/[…slug].js

    • Accessing Parameters:

    import { useRouter } from ‘next/router’;

    export default function Post() { const router = useRouter(); const { slug } = router.query;

    return

    Slug: {slug.join(‘/’)}

    ;
    }


    Nested routes allow you to structure files and directories for better organization:

    •  Example Structure:

    pages/
    blog/
    index.js -> /blog [slug].js -> /blog/:slug

    Additional Resources

    Learn More