Logo

dev-resources.site

for different kinds of informations.

Next.js: Dynamic Routing with API Integration.

Published at
11/27/2024
Categories
nextjs
routing
javascript
Author
remejuan
Categories
3 categories in total
nextjs
open
routing
open
javascript
open
Author
8 person written this
remejuan
open
Next.js: Dynamic Routing with API Integration.

The Idea

Next.js provides a file-based routing system that supports dynamic routes (e.g., /product/[id]). You can combine this with dynamic data fetching to create flexible and scalable applications. This is particularly useful for cases like e-commerce product pages, user profiles, or any content with unique identifiers.

Example: Dynamic Product Pages

1. Set Up the Dynamic Route

Create a file named [id].tsx inside a folder like /pages/product/:

pages/product/[id].tsx

2. Fetch Data for the Dynamic Route

// pages/product/[id].tsx

import { GetStaticPaths, GetStaticProps } from 'next';

type ProductProps = {
  product: {
    id: string;
    name: string;
    description: string;
    price: number;
  };
};

export default function ProductPage({ product }: ProductProps) {
  return (
    <div>
      <h1>{product.name}</h1>
      <p>{product.description}</p>
      <p>Price: ${product.price}</p>
    </div>
  );
}

// Generate dynamic paths for the product pages
export const getStaticPaths: GetStaticPaths = async () => {
  const res = await fetch('https://api.example.com/products');
  const products = await res.json();

  // Map over the products to define paths
  const paths = products.map((product: { id: string }) => ({
    params: { id: product.id },
  }));

  return {
    paths, // Pre-render these paths at build time
    fallback: 'blocking', // Dynamically render other pages on request
  };
};

// Fetch product data for each page
export const getStaticProps: GetStaticProps = async ({ params }) => {
  const res = await fetch(`https://api.example.com/products/${params?.id}`);
  const product = await res.json();

  // Pass the product data as props
  return {
    props: { product },
    revalidate: 10, // Revalidate every 10 seconds
  };
};
Enter fullscreen mode Exit fullscreen mode

3. Handle Non-existent Pages

To handle cases where the id doesn’t exist, return a notFound property in getStaticProps:

export const getStaticProps: GetStaticProps = async ({ params }) => {
  const res = await fetch(`https://api.example.com/products/${params?.id}`);

  if (res.status === 404) {
    return { notFound: true };
  }

  const product = await res.json();

  return {
    props: { product },
    revalidate: 10,
  };
};
Enter fullscreen mode Exit fullscreen mode

Key Features of This Approach:

  1. SEO-Friendly: Pages are pre-rendered with full HTML, making them great for search engines.

  2. Scalable: You can use fallback rendering (fallback: 'blocking') to dynamically generate pages for new data.

  3. Real-Time Updates: Combine with revalidate to ensure the data stays fresh without manual deployments.

  4. Error Handling: Handle 404s or other errors gracefully with notFound.

This method allows you to build highly dynamic and responsive web applications that scale easily!

routing Article's
30 articles in total
Favicon
Mastering Nested Navigation in Flutter with `go_router` and a Bottom Nav Bar
Favicon
Understanding ShellRoute in go_router: Managing Shared Layouts Effectively
Favicon
How the Web Evolved: The Rise of Single Page Applications
Favicon
Introducing Humiris MoAI Basic : A New Way to Build Hybrid AI Models
Favicon
TanStack Router: The Future of React Routing in 2025
Favicon
Next.js: Dynamic Routing with API Integration.
Favicon
Learning Next.js 13 App Router: A Comprehensive Guide 🚀
Favicon
Organizing Your Routes Modularly and Automatically in Lithe
Favicon
Organizando Suas Rotas de Forma Modular e Automática no Lithe
Favicon
🗺️ Peta Jalan Laravel: Menjelajah Routing, Middleware, dan Controller (Indonesian Version)
Favicon
Working On a React / Python Flask Back End Web App.
Favicon
Vue.js for Beginners 2024 #VueJs Part 5 : A Complete Guide to Routing with Vue Router
Favicon
Mastering Routing Protocols with Cisco Packet Tracer: A Learning Experience
Favicon
Restful Routing - A Flask API Example
Favicon
Routing in React vs. Next.js: Extra Work or Easy Wins?
Favicon
Browser refresh on click of Home button using href
Favicon
Decorate the Symfony router to add a trailing slash to all URLs
Favicon
Routing in Umbraco Part 2: Content Finders
Favicon
Routing in Umbraco Part 1: URL segments
Favicon
Simplifying Network Administration: BGP Route Servers' Function in the Internet Ecosystem
Favicon
createBrowserRouter A step up from Switch
Favicon
Mastering Angular 17 Routing
Favicon
Snag the Current URL in SvelteKit (2024 Edition)
Favicon
Ensuring Type Safety in Next.js Routing
Favicon
Laravel 11: Health Check Routing Example
Favicon
Switch'in L2 mi L3 mü Olduğunun Öğrenilmesi
Favicon
Routing with React Router
Favicon
Routing implementation using PHP attributes
Favicon
What is Vinxi, and how does it compare to Vike?
Favicon
Fallback Routing with Axum

Featured ones: