getStaticProps

getStaticProps adlı bir işlevin dışa aktarılması, işlevden döndürülen prop'ları kullanarak derleme zamanında bir sayfayı önceden oluşturacaktır:

pages/index.tsx
import type { InferGetStaticPropsType, GetStaticProps } from 'next'
 
type Repo = {
  name: string
  stargazers_count: number
}
 
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
}

getStaticProps adresinde kullanmak üzere modülleri üst düzey kapsamda içe aktarabilirsiniz. Kullanılan içe aktarmalar istemci tarafı için paketlenmeyecektir. Bu, veritabanınızdan veri almak da dahil olmak üzere sunucu tarafı kodunu doğrudan getStaticProps adresinde yazabileceğiniz anlamına gelir.

Context parameter

context parametresi aşağıdaki anahtarları içeren bir nesnedir:

NameDescription
paramsContains the route parameters for pages using dynamic routes. For example, if the page name is [id].js, then params will look like { id: ... }. You should use this together with getStaticPaths, which we'll explain later.
preview(Deprecated for draftMode) preview is true if the page is in the Preview Mode and false otherwise.
previewData(Deprecated for draftMode) The preview data set by setPreviewData.
draftModedraftMode is true if the page is in the Draft Mode and false otherwise.
localeContains the active locale (if enabled).
localesContains all supported locales (if enabled).
defaultLocaleContains the configured default locale (if enabled).

getStaticProps return values

getStaticProps işlevi, props, redirect veya notFound ve ardından isteğe bağlı bir revalidate özelliği içeren bir nesne döndürmelidir.

props

props nesnesi, her bir değerin sayfa bileşeni tarafından alındığı bir anahtar-değer çiftidir. Serileştirilebilir bir nesne olmalıdır böylece aktarılan herhangi bir sahne aşağıdakilerle serileştirilebilir JSON.stringify.

export async function getStaticProps(context) {
  return {
    props: { message: `Next.js is awesome` }, // will be passed to the page component as props
  }
}

revalidate

revalidate özelliği, sayfanın yeniden oluşturulabileceği saniye cinsinden miktardır (varsayılan değer false veya yeniden doğrulama yok).

// This function gets called at build time on server-side.
// It may be called again, on a serverless function, if
// revalidation is enabled and a new request comes in
export async function getStaticProps() {
  const res = await fetch('https://.../posts')
  const posts = await res.json()
 
  return {
    props: {
      posts,
    },
    // Next.js will attempt to re-generate the page:
    // - When a request comes in
    // - At most once every 10 seconds
    revalidate: 10, // In seconds
  }
}

Artımlı Statik Rejenerasyon hakkında daha fazla bilgi edinin.

ISR'den yararlanan bir sayfanın önbellek durumu x-nextjs-cache yanıt başlığının değeri okunarak belirlenebilir. Olası değerler şunlardır:

notFound

notFound boolean'ı sayfanın bir 404 durumu ve 404 Sayfası döndürmesini sağlar. notFound: true ile, daha önce başarıyla oluşturulmuş bir sayfa olsa bile sayfa bir 404 döndürür. Bu, kullanıcı tarafından oluşturulan içeriğin yazarı tarafından kaldırılması gibi kullanım durumlarını desteklemek içindir. Unutmayın, notFound burada açıklanan revalidate davranışının aynısını izler.

export async function getStaticProps(context) {
  const res = await fetch(`https://.../data`)
  const data = await res.json()
 
  if (!data) {
    return {
      notFound: true,
    }
  }
 
  return {
    props: { data }, // will be passed to the page component as props
  }
}

Bilmekte fayda var: notFound için gerekli değildir fallback: false modunda yalnızca getStaticPaths adresinden döndürülen yollar önceden işlenecektir.

redirect

redirect nesnesi dahili veya harici kaynaklara yönlendirmeye izin verir. { destination: string, permanent: boolean } şekliyle eşleşmelidir.

Bazı nadir durumlarda, eski HTTP istemcilerinin düzgün şekilde yönlendirilmesi için özel bir durum kodu atamanız gerekebilir. Bu durumlarda, permanent özelliği yerine statusCode özelliğini kullanabilirsiniz, ancak ikisini birden kullanamazsınız. Ayrıca basePath: false 'u next.config.js'daki yönlendirmelere benzer şekilde ayarlayabilirsiniz.

export async function getStaticProps(context) {
  const res = await fetch(`https://...`)
  const data = await res.json()
 
  if (!data) {
    return {
      redirect: {
        destination: '/',
        permanent: false,
        // statusCode: 301
      },
    }
  }
 
  return {
    props: { data }, // will be passed to the page component as props
  }
}

Yönlendirmeler derleme zamanında biliniyorsa, bunlar next.config.js onun yerine.

Reading files: Use process.cwd()

Dosyalar getStaticProps adresindeki dosya sisteminden doğrudan okunabilir.

Bunu yapmak için bir dosyanın tam yolunu almanız gerekir.

Next.js kodunuzu ayrı bir dizinde derlediğinden, döndürdüğü yol Pages Router'dan farklı olacağından __dirname adresini kullanamazsınız.

Bunun yerine Next.js'nin çalıştırıldığı dizini veren process.cwd() adresini kullanabilirsiniz.

import { promises as fs } from 'fs'
import path from 'path'
 
// posts will be populated at build time by getStaticProps()
function Blog({ posts }) {
  return (
    <ul>
      {posts.map((post) => (
        <li>
          <h3>{post.filename}</h3>
          <p>{post.content}</p>
        </li>
      ))}
    </ul>
  )
}
 
// This function gets called at build time on server-side.
// It won't be called on client-side, so you can even do
// direct database queries.
export async function getStaticProps() {
  const postsDirectory = path.join(process.cwd(), 'posts')
  const filenames = await fs.readdir(postsDirectory)
 
  const posts = filenames.map(async (filename) => {
    const filePath = path.join(postsDirectory, filename)
    const fileContents = await fs.readFile(filePath, 'utf8')
 
    // Generally you would parse/transform the contents
    // For example you can transform markdown to HTML here
 
    return {
      filename,
      content: fileContents,
    }
  })
  // By returning { props: { posts } }, the Blog component
  // will receive `posts` as a prop at build time
  return {
    props: {
      posts: await Promise.all(posts),
    },
  }
}
 
export default Blog

Version History

VersionChanges
v13.4.0App Router is now stable with simplified data fetching
v12.2.0On-Demand Incremental Static Regeneration is stable.
v12.1.0On-Demand Incremental Static Regeneration added (beta).
v10.0.0locale, locales, defaultLocale, and notFound options added.
v10.0.0fallback: 'blocking' return option added.
v9.5.0Stable Incremental Static Regeneration
v9.3.0getStaticProps introduced.