Skip to content

Instantly share code, notes, and snippets.

@Ningensei848
Last active January 7, 2022 14:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Ningensei848/882e27fb8f0f02bde390e85f9606a537 to your computer and use it in GitHub Desktop.
Save Ningensei848/882e27fb8f0f02bde390e85f9606a537 to your computer and use it in GitHub Desktop.

[SSG] PageTemplate.tsx for Next.js

import type { NextPage, GetStaticPaths, InferGetStaticPropsType, GetStaticPropsContext } from 'next'

type Props = InferGetStaticPropsType<typeof getStaticProps>

export const getStaticPaths: GetStaticPaths = async () => {
  return {
    paths: [
      { params: {} }
    ],
    fallback: true // false, or 'blocking'
  };
}

export const getStaticProps = async (context: GetStaticPropsContext) => {
  return {
    props: {},
  }
}

const PageComponent: NextPage<Props> = (props) => {
  return <>...</>
}

export default PageComponent

Reference

import type { NextPage, GetStaticPaths, InferGetStaticPropsType, GetStaticPropsContext } from 'next'
type Props = InferGetStaticPropsType<typeof getStaticProps>
// This function gets called at build time
export const getStaticPaths: GetStaticPaths = async () => {
// Call an external API endpoint to get posts
const res = await fetch('https://.../posts')
const posts = await res.json()
// Get the paths we want to pre-render based on posts
// cf. https://nextjs.org/docs/basic-features/data-fetching#the-paths-key-required
const paths = posts.map((post) => ({
params: { id: post.id }
}))
// We'll pre-render only these paths at build time.
// { fallback: false } means other routes should 404.
return { paths, fallback: false }
}
// This also gets called at build time
export const getStaticProps = async (context: GetStaticPropsContext) => {
// params contains the post `id`.
// If the route is like /posts/1, then params.id is 1
const res = await fetch(`https://.../posts/${params.id}`)
const post = await res.json()
// Pass post data to the page via props
return { props: { post } }
}
const PageComponent: NextPage<Props> = (props) => {
return <>...</>
}
export default PageComponent
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment