Go Pro Sign Up Login
0 days 0 hrs 0 min 0 sec

Summer Sale

50% off Level Up Pro until you unsubscribe.
Get access to ALL 128 courses on Level Up Tutorials

This is your last chance to get Level Up Pro for $145/year.

or Learn More
Moon Moon

Buy Now and unlock this series

$

39

.99

$

29

.99

yours forever

Become a Pro and unlock everything

$

24

.99

per month

Custom Server Page Routes

This video is about #7 Custom Server Page Routes

Downloads

Become a pro to download code and videos

Comments

Nathan

almost 2 years ago [edited]

Hi guys,

So Next.js has made it much easier now to do dynamic routing. All you need to do is make a posts directory in pages (/pages/posts) then make a js file called [id].js (or whatever placeholder you want, [slug].js etc.)

You are now required to use getStaticPaths() with getStaticProps() to fetch data from an external api with dynamic routing. This is how I achieved the result (for some reason I need to parse the html for the content with the Local by Flywheel or all HTML markup returns as a string):

import { Config } from "../../config";
import parse from "html-react-parser";

export default function Post({ post }) {
  const content = parse(post.content.rendered);

  return (
    <div>
      <h1>{post.title.rendered}</h1>
      {content}
    </div>
  );
}

export async function getStaticPaths() {
  const res = await fetch(`${Config.apiUrl}/wp-json/wp/v2/posts`);
  const posts = await res.json();

  const paths = posts.map((post) => ({
    params: { id: post.id.toString() },
  }));

  return { paths, fallback: false };
}

export async function getStaticProps({ params }) {
  const res = await fetch(`${Config.apiUrl}/wp-json/wp/v2/posts/${params.id}`);
  const post = await res.json();
  return {
    props: {
      post,
    },
  };
}

Want to join the conversation?

Become a Pro member today!