Data Fetching
i18n

Nov 2021

Data fetching

`getStaticProps`

`getStaticPaths`

`getServerSideProps`

`getInitialProps` ⚠️

props during build time

paths for dynamic routes

props for each request

getServerSideProps

Client-side navigation

makes one fetch request  to retrieve `props`

only runs on the server

Server Request

returns the necessary `props` so the page re-renders

getStaticProps

Seriealized data

generates a JSON with the result for client-side navigation

only runs on build

revalidate

when provided, page will rebuild without needing to deploy everything again

getStaticPaths

Dynamic routes

page components for non-predefined paths

e.g.: `[slug].tsx`

for dynamic routes

fallback

false:  unmatched route returns `404`

blocking:  will SSR unmatched paths on-demand

true:  serves fallback version for unmatched paths

Static Paths combo

`getStaticPaths` returns a list of paths and calls `getStaticProps`

needs to use getStaticProps

Rendering Strategies

SSPR

Server-Side Pre-Rendered

export const Post = ({ title, content }) => (
  <main>
    <h1>{post.title}</h1>
    <article>{content}</article>
  </main>
)

export async function getStaticProps(context) {
  const res = await getPost('post-slug')
  const { title, content } = await res.json()

  return {
    props: {
      title,
      content
    },
  }
}

ISR

Incrementally Statically Regenerated

export const Post = ({ title, content }) => (
  <main>
    <h1>{post.title}</h1>
    <article>{content}</article>
  </main>
)

export async function getStaticProps(context) {
  const res = await getPost('post-slug')
  const { title, content } = await res.json()

  return {
    props: {
      title,
      content
    },
    revalidate: 6 * 60 // time in seconds
  }
}

SSR

Server-Side Rendered

export const Post = ({ title, content }) => (
  <main>
    <h1>{post.title}</h1>
    <article>{content}</article>
  </main>
)

export async function getServerSideProps(context) {
  const res = await getPost('post-slug')
  const { title, content } = await res.json()

  return {
    props: {
      title,
      content
    },
  }
}

Dynamic routes

export async function getStaticProps(context) {
  const res = await getPostInfo(context.params.id)
  const { title, content } = await res.json()

  return {
    props: {
      title,
      content
    },
  }
}

export async function getStaticPaths() {
  const postPaths = await getAllPostsFromDir(path.join(process.cwd, 'posts'))
  return {
    paths: postPaths,
    fallback: false
  }
}

Lazy-Rendering

internationalization

Out-of-the-box

i18n routes

default locale

locales allow-list

Header sniffing

router support

Black Belt [Day 2]

By Atila

Black Belt [Day 2]

  • 352