Skip to main content

How to use Dynamic Route in Next.js (described as Static Site Generation (SSG))

💡 To use Dynamic Route in Next.js, You must use getStaticPaths, getStaticProps.

getStaticPaths

getStaticPaths uses a server to pre-render all pages according to all URLs at the build time to create static pages with dynamic paths.

For example, if you have dynamic routing called /post/[id].tsx, you can create a file that pre-renders HTML, JS, etc. for /post/1, /post/2, /post/3,

During this deployment, when /post/1 is called, HTML, JS, etc. of pre-rendered /post/1 are rendered to the browser.

getStaticProps

The path (/post/1) is then passed to getStaticProps so that data for that path can be imported.

It is the Next.js API that can be confused with useEffect,

The difference is that for useEffect is calling in Client-Side so that the data can be imported from the API

On the other hand, getStaticProps allows the server to call and retrieve data from the API.

useEffectgetStaticProps
Where to runOn Client-SideOn Server-Side
When to runAfter Component renderingAt Next.js build time
Data Sourceexternal data source(server API, database etc)- usually internal data source(local file, database etc)
- server API call available
How to runrun When you needrun at pre-rendering once

If there is no dynamic path, only getStaticProps is used to import data from the server from the API

You can give data to the Client-Side.

(getStaticPaths cannot be used alone. But getStaticProps is available on its own.)

getStaticPaths + getStaticProps

if you use getStaticPaths and getStaticProps, then this is called Static Site Generation(SSG)

(Server Side Rendering(SSR) would be covered later)

// /pages/post/[id].tsximport React, { useEffect, useState } from "react";

const Post = (data: IData) => {
if (!data) return null;

return (
<MarkdownContainer>
<div>{data}</div>
</MarkdownContainer>
);
};

export default Post;

export const getStaticPaths = () => {
return {
paths: [
{ id: "1" },
{ id: "2" },
{ id: "3" },
],
// true, false, "blocking"
fallback: true,
};
};

export const getStaticProps = ({ params }: { id: string }) => {
const res = await fetch('https://API_OR_SOMETHING.com/v2/getData');
const data = await res.json();

return {
props: {
data,
},
};
};