Movatterモバイル変換


[0]ホーム

URL:


Skip to content
Important
Security Advisory: React2Shell & two new vulnerabilities
Find out more

getStaticProps

Last updated June 10, 2025

Exporting a function calledgetStaticProps will pre-render a page at build time using the props returned from the function:

pages/index.tsx
importtype { InferGetStaticPropsType, GetStaticProps }from'next'typeRepo= {  name:string  stargazers_count:number}exportconstgetStaticProps= (async (context)=> {constres=awaitfetch('https://api.github.com/repos/vercel/next.js')constrepo=awaitres.json()return { props: { repo } }})satisfiesGetStaticProps<{  repo:Repo}>exportdefaultfunctionPage({  repo,}:InferGetStaticPropsType<typeof getStaticProps>) {returnrepo.stargazers_count}

You can import modules in top-level scope for use ingetStaticProps. Imports used willnot be bundled for the client-side. This means you can writeserver-side code directly ingetStaticProps, including fetching data from your database.

Context parameter

Thecontext parameter is an object containing the following keys:

NameDescription
paramsContains the route parameters for pages usingdynamic routes. For example, if the page name is[id].js, thenparams will look like{ id: ... }. You should use this together withgetStaticPaths, which we'll explain later.
preview(Deprecated fordraftMode)preview istrue if the page is in thePreview Mode andfalse otherwise.
previewData(Deprecated fordraftMode) Thepreview data set bysetPreviewData.
draftModedraftMode istrue if the page is in theDraft Mode andfalse otherwise.
localeContains the active locale (if enabled).
localesContains all supported locales (if enabled).
defaultLocaleContains the configured default locale (if enabled).
revalidateReasonProvides a reason for why the function was called. Can be one of: "build" (run at build time), "stale" (revalidate period expired, or running indevelopment mode), "on-demand" (triggered viaon-demand revalidation)

getStaticProps return values

ThegetStaticProps function should return an object containing eitherprops,redirect, ornotFound followed by anoptionalrevalidate property.

props

Theprops object is a key-value pair, where each value is received by the page component. It should be aserializable object so that any props passed, could be serialized withJSON.stringify.

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

revalidate

Therevalidate property is the amount in seconds after which a page re-generation can occur (defaults tofalse or no revalidation).

// 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 inexportasyncfunctiongetStaticProps() {constres=awaitfetch('https://.../posts')constposts=awaitres.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  }}

Learn more aboutIncremental Static Regeneration.

The cache status of a page leveraging ISR can be determined by reading the value of thex-nextjs-cache response header. The possible values are the following:

  • MISS - the path is not in the cache (occurs at most once, on the first visit)
  • STALE - the path is in the cache but exceeded the revalidate time so it will be updated in the background
  • HIT - the path is in the cache and has not exceeded the revalidate time

notFound

ThenotFound boolean allows the page to return a404 status and404 Page. WithnotFound: true, the page will return a404 even if there was a successfully generated page before. This is meant to support use cases like user-generated content getting removed by its author. Note,notFound follows the samerevalidate behaviordescribed here.

exportasyncfunctiongetStaticProps(context) {constres=awaitfetch(`https://.../data`)constdata=awaitres.json()if (!data) {return {      notFound:true,    }  }return {    props: { data },// will be passed to the page component as props  }}

Good to know:notFound is not needed forfallback: false mode as only paths returned fromgetStaticPaths will be pre-rendered.

redirect

Theredirect object allows redirecting to internal or external resources. It should match the shape of{ destination: string, permanent: boolean }.

In some rare cases, you might need to assign a custom status code for olderHTTP clients to properly redirect. In these cases, you can use thestatusCode property instead of thepermanent property,but not both. You can also setbasePath: false similar to redirects innext.config.js.

exportasyncfunctiongetStaticProps(context) {constres=awaitfetch(`https://...`)constdata=awaitres.json()if (!data) {return {      redirect: {        destination:'/',        permanent:false,// statusCode: 301      },    }  }return {    props: { data },// will be passed to the page component as props  }}

If the redirects are known at build-time, they should be added innext.config.js instead.

Reading files: Useprocess.cwd()

Files can be read directly from the filesystem ingetStaticProps.

In order to do so you have to get the full path to a file.

Since Next.js compiles your code into a separate directory you can't use__dirname as the path it returns will be different from the Pages Router.

Instead you can useprocess.cwd() which gives you the directory where Next.js is being executed.

import { promisesas fs }from'fs'import pathfrom'path'// posts will be populated at build time by getStaticProps()functionBlog({ 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.exportasyncfunctiongetStaticProps() {constpostsDirectory=path.join(process.cwd(),'posts')constfilenames=awaitfs.readdir(postsDirectory)constposts=filenames.map(async (filename)=> {constfilePath=path.join(postsDirectory, filename)constfileContents=awaitfs.readFile(filePath,'utf8')// Generally you would parse/transform the contents// For example you can transform markdown to HTML herereturn {      filename,      content: fileContents,    }  })// By returning { props: { posts } }, the Blog component// will receive `posts` as a prop at build timereturn {    props: {      posts:awaitPromise.all(posts),    },  }}exportdefault 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, andnotFound options added.
v10.0.0fallback: 'blocking' return option added.
v9.5.0StableIncremental Static Regeneration
v9.3.0getStaticProps introduced.

Was this helpful?

supported.

[8]ページ先頭

©2009-2025 Movatter.jp