fetch from mdx using getStaticProps

Nextra (opens in a new tab) has 12003 stars on GitHub!

The output above was produced by this code:

import { useData } from 'nextra/data'
 
export const getStaticProps = ({ params }) => {
  return fetch(`https://api.github.com/repos/shuding/nextra`)
    .then(res => res.json())
    .then(repo => ({
      props: {
        // We add an `ssg` field to the page props,
        // which will be provided to the Nextra `useData` hook.
        ssg: {
          stars: repo.stargazers_count
        }
      },
      // The page will be considered as stale and regenerated every 60 seconds.
      revalidate: 60
    }))
}
 
export const Stars = () => {
  // Get the data from SSG, and render it as a component.
  const { stars } = useData()
  return <strong>{stars}</strong>
}
 
Nextra has <Stars /> stars on GitHub!

Version 3 Update

In version 3 of Nextra useData was moved to nextra/hooks:

import { useData } from 'nextra/hooks'

getStaticProps

With Next.js, you can pre-render your page using Static Generation (SSG) (opens in a new tab). Your pages will be generated at build time and statically served to visitors. It can also be cached by a CDN to maximize the performance.

This is supported by Nextra too. See section Next.js SSG (opens in a new tab).

If you export a function called getStaticProps (Static Site Generation) from a page, Next.js will pre-render this page at build time using the props returned by getStaticProps.

See also

See also the example in section fetch with variable server