DEV Community

Cover image for Creating Dynamic Pages with Next.js and Fetching Data from a REST API
JinChul Moon
JinChul Moon

Posted on

Creating Dynamic Pages with Next.js and Fetching Data from a REST API

In this tutorial, we’ll go over how to create dynamic pages in Next.js using React and REST API integration. This approach allows us to fetch data dynamically and render it on the page.

  1. Creating the REST API Endpoint in WordPress

First, we use WordPress to expose a REST API that provides our content. In this case, we are fetching portfolio items via the API endpoint:

https://creative-moon.com/wp-json/wp/v2/portfolio?per_page=100
Enter fullscreen mode Exit fullscreen mode

This endpoint returns a list of portfolio items, which we can then use in Next.js to render pages dynamically.

  1. Fetching Data in Next.js with getStaticPaths and getStaticProps

Next, we use getStaticPaths and getStaticProps in Next.js to generate dynamic pages based on the fetched data.

// src/pages/works/[slug].tsx

import { GetStaticProps, GetStaticPaths } from 'next';

export const getStaticPaths: GetStaticPaths = async () => {
  const res = await fetch('https://creative-moon.com/wp-json/wp/v2/portfolio?per_page=100');
  const posts = await res.json();

  // Generating paths based on the slug
  const paths = posts.map((post: any) => ({
    params: { slug: post.slug },
  }));

  return {
    paths,
    fallback: 'blocking',  // The page will wait to be generated before serving
  };
};

export const getStaticProps: GetStaticProps = async ({ params }) => {
  const res = await fetch(`https://creative-moon.com/wp-json/wp/v2/portfolio?slug=${params?.slug}`);
  const postData = await res.json();

  if (!postData || postData.length === 0) {
    return { notFound: true };  // Return 404 if no data is found
  }

  const post = postData[0];

  return {
    props: { post },
    revalidate: 60,  // Revalidate the page every 60 seconds
  };
};

const WorkDetail = ({ post }: { post: any }) => {
  if (!post) return <div>Loading...</div>;  // Show loading if the data is still fetching

  return (
    <div>
      <h1>{post.title.rendered}</h1>
      <div>{post.content.rendered}</div>  {/* Render the content fetched from the API */}
    </div>
  );
};

export default WorkDetail;
Enter fullscreen mode Exit fullscreen mode
  1. Explanation of getStaticPaths and getStaticProps
  • getStaticPaths: This function is responsible for generating dynamic routes. It fetches data from the REST API, extracts the slug for each post, and uses it to generate paths that Next.js will build statically.
  • getStaticProps: This function fetches the data for a specific post based on the slug. It fetches content dynamically from the REST API and passes it as props to the page component.
  1. Rendering Dynamic Pages

With Next.js, dynamic pages are created based on the slug of each portfolio post. The title and content of each post are fetched from the API and displayed on the page.

// Inside the WorkDetail component
const WorkDetail = ({ post }: { post: any }) => {
  if (!post) return <div>Loading...</div>;

  return (
    <div>
      <h1>{post.title.rendered}</h1>  // Dynamically render post title
      <div>{post.content.rendered}</div>  // Dynamically render post content
    </div>
  );
};
Enter fullscreen mode Exit fullscreen mode
  1. Final Outcome
  • When navigating to http://localhost:3000/works/{slug}, Next.js will fetch the data from the REST API and display the content dynamically on the page.
  • This method allows Next.js to generate static pages based on dynamic data fetched from WordPress.

By using this method, you can easily fetch and render dynamic content from REST APIs in Next.js, making it ideal for headless CMS like WordPress. The combination of static generation and server-side rendering in Next.js powers this integration effectively.

I spent hours today troubleshooting a small issue with pages/works/[slug].tsx. It turned out to be a simple path problem, but after checking and fixing the file structure, everything started working as expected. It was frustrating but rewarding to finally resolve it!

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

Top comments (0)

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

👋 Kindness is contagious

Explore a trove of insights in this engaging article, celebrated within our welcoming DEV Community. Developers from every background are invited to join and enhance our shared wisdom.

A genuine "thank you" can truly uplift someone’s day. Feel free to express your gratitude in the comments below!

On DEV, our collective exchange of knowledge lightens the road ahead and strengthens our community bonds. Found something valuable here? A small thank you to the author can make a big difference.

Okay