You can get in-depth information about getStaticProps
in our documentation. But here is some essential information you should know about getStaticProps
.
In our lib/posts.js
, we’ve implemented getSortedPostsData
which fetches data from the file system. But you can fetch the data from other sources, like an external API endpoint, and it’ll work just fine:
import fetch from 'node-fetch' export async function getSortedPostsData() { // Instead of the file system, // fetch post data from an external API endpoint const res = await fetch('..') return res.json() }
You can also query the database directly:
import someDatabaseSDK from 'someDatabaseSDK' const databaseClient = someDatabaseSDK.createClient(...) export async function getSortedPostsData() { // Instead of the file system, // fetch post data from a database return databaseClient.query('SELECT posts...') }
This is possible because getStaticProps
runs only on the server-side. It will never be run on the client-side. It won’t even be included in the JS bundle for the browser. That means you can write code such as direct database queries without them being sent to browsers.
npm run dev
or yarn dev
), getStaticProps
runs on every request.getStaticProps
runs at build time.Because it’s meant to be run at build time, you won’t be able to use data that’s only available during request time, such as query parameters or HTTP headers.
getStaticProps
can only be exported from a page. You can’t export it from non-page files.
One of the reasons for this restriction is that React needs to have all the required data before the page is rendered.
Static Generation is not a good idea if you cannot pre-render a page ahead of a user's request. Maybe your page shows frequently updated data, and the page content changes on every request.
In cases like this, you can try Server-side Rendering or skipping pre-rendering. Let’s talk about these strategies before we move on to the next lesson.