How to Use Static Site Generation in Next.js for Fast Pages
In Next.js, use
getStaticProps inside a page component to enable static site generation (SSG). This function runs at build time to fetch data and pre-render the page as static HTML, improving performance and SEO.Syntax
Static Site Generation in Next.js uses the getStaticProps function exported from a page. This function runs at build time and returns props for the page component.
export async function getStaticProps(): Fetches data before build.return { props: { ... } }: Passes data as props to the page.- The page component receives these props and renders static HTML.
javascript
export async function getStaticProps() { // Fetch data here const data = await fetchData(); return { props: { data } }; } export default function Page({ data }) { return <div>{data.message}</div>; }
Example
This example shows a Next.js page that uses getStaticProps to fetch a message at build time and display it. The page is pre-rendered as static HTML for fast loading.
javascript
export async function getStaticProps() { // Simulate fetching data const data = { message: 'Hello from static site generation!' }; return { props: { data } }; } export default function HomePage({ data }) { return <main> <h1>{data.message}</h1> </main>; }
Output
<main>
<h1>Hello from static site generation!</h1>
</main>
Common Pitfalls
- Not exporting
getStaticPropscorrectly or forgetting to export it causes the page to render without static props. - Using data that changes often without
revalidateleads to stale content. - Trying to use
getStaticPropsin non-page components will not work. - Fetching data that depends on request-time info (like user session) is not possible with SSG.
javascript
/* Wrong: getStaticProps inside a component file that is not a page */ function Component() { return <div>Hi</div>; } export async function getStaticProps() { return { props: { message: 'Hello' } }; } export default Component; /* Right: getStaticProps only in page files */ export async function getStaticProps() { return { props: { message: 'Hello' } }; } export default function Page({ message }) { return <div>{message}</div>; }
Quick Reference
Key points to remember when using static site generation in Next.js:
- Use
getStaticPropsonly in page components. - Runs at build time to generate static HTML.
- Props returned from
getStaticPropsare passed to the page. - Use
revalidateto enable incremental static regeneration for fresh data. - Not suitable for data that changes per request or user.
Key Takeaways
Use getStaticProps in page files to fetch data at build time for static site generation.
Static pages load faster and improve SEO because they are pre-rendered as HTML.
Do not use getStaticProps in non-page components; it only works in pages.
Use the revalidate option for incremental static regeneration to update static pages after build.
Static site generation is best for content that does not change on every request.