getStaticPaths

Dinamik Rotalar kullanan bir sayfadan getStaticPaths adlı bir işlev dışa aktarıldığında Next.js, getStaticPaths tarafından belirtilen tüm yolları statik olarak önceden oluşturacaktır.

pages/repo/[name].tsx
import type {
  InferGetStaticPropsType,
  GetStaticProps,
  GetStaticPaths,
} from 'next'
 
type Repo = {
  name: string
  stargazers_count: number
}
 
export const getStaticPaths = (async () => {
  return {
    paths: [
      {
        params: {
          name: 'next.js',
        },
      }, // See the "paths" section below
    ],
    fallback: true, // false or "blocking"
  }
}) satisfies GetStaticPaths
 
export const getStaticProps = (async (context) => {
  const res = await fetch('https://api.github.com/repos/vercel/next.js')
  const repo = await res.json()
  return { props: { repo } }
}) satisfies GetStaticProps<{
  repo: Repo
}>
 
export default function Page({
  repo,
}: InferGetStaticPropsType<typeof getStaticProps>) {
  return repo.stargazers_count
}

getStaticPaths return values

getStaticPaths işlevi aşağıdaki gerekli özelliklere sahip bir nesne döndürmelidir:

paths

paths anahtarı hangi yolların önceden oluşturulacağını belirler. Örneğin, pages/posts/[id].js adında Dinamik Rotalar kullanan bir sayfanız olduğunu varsayalım. Bu sayfadan getStaticPaths adresini dışa aktarırsanız ve paths için aşağıdakileri döndürürseniz:

return {
  paths: [
    { params: { id: '1' }},
    {
      params: { id: '2' },
      // with i18n configured the locale for the path can be returned as well
      locale: "en",
    },
  ],
  fallback: ...
}

Ardından Next.js, pages/posts/[id].js adresindeki sayfa bileşenini kullanarak next build sırasında /posts/1 ve /posts/2 adreslerini statik olarak oluşturacaktır.

Her params nesnesi için değer, sayfa adında kullanılan parametrelerle eşleşmelidir:

params dizeleri büyük/küçük harfe duyarlıdır ve yolların doğru şekilde oluşturulmasını sağlamak için ideal olarak normalleştirilmelidir. Örneğin, bir parametre için WoRLD döndürülürse, world veya World değil, yalnızca WoRLD ziyaret edilen gerçek yol ise eşleşecektir.

params nesnesinden ayrı olarak, i18n yapılandırıldığında, oluşturulmakta olan yol için yerel ayarı yapılandıran bir locale alanı döndürülebilir.

fallback: false

Eğer fallback false ise, getStaticPaths tarafından döndürülmeyen tüm yollar 404 sayfası ile sonuçlanacaktır.

next build çalıştırıldığında Next.js, getStaticPaths adresinin fallback: false adresini döndürüp döndürmediğini kontrol edecek ve ardından yalnızca getStaticPaths tarafından döndürülen yolları oluşturacaktır. Bu seçenek, oluşturmanız gereken az sayıda yol varsa veya yeni sayfa verileri sık eklenmiyorsa kullanışlıdır. Daha fazla yol eklemeniz gerektiğini fark ederseniz ve fallback: false adresiniz varsa, yeni yolların oluşturulabilmesi için next build adresini tekrar çalıştırmanız gerekecektir.

Aşağıdaki örnek, pages/posts/[id].js adlı sayfa başına bir blog gönderisini önceden işler. Blog gönderilerinin listesi bir CMS'den getirilecek ve getStaticPaths tarafından döndürülecektir. Ardından, her sayfa için gönderi verilerini bir CMS'den getStaticProps.

pages/posts/[id].js
function Post({ post }) {
  // Render post...
}
 
// This function gets called at build time
export async function getStaticPaths() {
  // Call an external API endpoint to get posts
  const res = await fetch('https://.../posts')
  const posts = await res.json()
 
  // Get the paths we want to pre-render based on posts
  const paths = posts.map((post) => ({
    params: { id: post.id },
  }))
 
  // We'll pre-render only these paths at build time.
  // { fallback: false } means other routes should 404.
  return { paths, fallback: false }
}
 
// This also gets called at build time
export async function getStaticProps({ params }) {
  // params contains the post `id`.
  // If the route is like /posts/1, then params.id is 1
  const res = await fetch(`https://.../posts/${params.id}`)
  const post = await res.json()
 
  // Pass post data to the page via props
  return { props: { post } }
}
 
export default Post

fallback: true

Examples

Eğer fallback, true ise, getStaticProps 'nin davranışı aşağıdaki şekillerde değişir:

Bilmenizde fayda var: fallback: true adresi kullanılırken desteklenmez output: 'export'.

When is fallback: true useful?

fallback: true Uygulamanızda veriye bağlı çok sayıda statik sayfa varsa (çok büyük bir e-ticaret sitesi gibi) kullanışlıdır. Tüm ürün sayfalarını önceden render etmek istiyorsanız, derlemeler çok uzun zaman alacaktır.

Bunun yerine, sayfaların küçük bir alt kümesini statik olarak oluşturabilir ve geri kalanı için fallback: true adresini kullanabilirsiniz. Birisi henüz oluşturulmamış bir sayfayı talep ettiğinde, kullanıcı sayfayı bir yükleme göstergesi veya iskelet bileşeni ile görecektir.

Kısa bir süre sonra, getStaticProps tamamlanır ve sayfa istenen verilerle işlenir. Şu andan itibaren, aynı sayfayı isteyen herkes statik olarak önceden oluşturulmuş sayfayı alacaktır.

Bu, kullanıcıların her zaman hızlı bir deneyim yaşamasını sağlarken hızlı derlemeleri ve Statik Üretimin avantajlarını korur.

fallback: true oluşturulan sayfaları güncellemeyecektir, bunun için Artımlı Statik Yenileme'ye göz atın.

fallback: 'blocking'

fallback, 'blocking' ise, getStaticPaths tarafından döndürülmeyen yeni yollar, SSR ile aynı şekilde HTML 'un oluşturulmasını bekleyecek (bu nedenle engelleme) ve daha sonra gelecekteki istekler için önbelleğe alınacak, böylece her yol için yalnızca bir kez gerçekleşecektir.

getStaticProps aşağıdaki gibi davranacaktır:

fallback: 'blocking' varsayılan olarak oluşturulan sayfaları güncellemeyecektir. Oluşturulan sayfaları güncellemek için fallback: 'blocking' ile birlikte Artan Statik Yenileme özelliğini kullanın.

Bilmenizde fayda var: fallback: 'blocking' adresi kullanılırken desteklenmez output: 'export'.

Fallback pages

Bir sayfanın "yedek" sürümünde:

Aşağıdaki örnekte isFallback adresinin kullanımı gösterilmektedir:

pages/posts/[id].js
import { useRouter } from 'next/router'
 
function Post({ post }) {
  const router = useRouter()
 
  // If the page is not yet generated, this will be displayed
  // initially until getStaticProps() finishes running
  if (router.isFallback) {
    return <div>Loading...</div>
  }
 
  // Render post...
}
 
// This function gets called at build time
export async function getStaticPaths() {
  return {
    // Only `/posts/1` and `/posts/2` are generated at build time
    paths: [{ params: { id: '1' } }, { params: { id: '2' } }],
    // Enable statically generating additional pages
    // For example: `/posts/3`
    fallback: true,
  }
}
 
// This also gets called at build time
export async function getStaticProps({ params }) {
  // params contains the post `id`.
  // If the route is like /posts/1, then params.id is 1
  const res = await fetch(`https://.../posts/${params.id}`)
  const post = await res.json()
 
  // Pass post data to the page via props
  return {
    props: { post },
    // Re-generate the post at most once per second
    // if a request comes in
    revalidate: 1,
  }
}
 
export default Post

Version History

VersionChanges
v13.4.0App Router is now stable with simplified data fetching, including generateStaticParams()
v12.2.0On-Demand Incremental Static Regeneration is stable.
v12.1.0On-Demand Incremental Static Regeneration added (beta).
v9.5.0Stable Incremental Static Regeneration
v9.3.0getStaticPaths introduced.