xxxxxxxxxx
export async function getServerSideProps(context) {
return {
props: {}, // will be passed to the page component as props
}
}
xxxxxxxxxx
function Page({ data }) {
// Render data...
}
// This gets called on every request
export async function getServerSideProps() {
// Fetch data from external API
const res = await fetch(`https://.../data`)
const data = await res.json()
// Pass data to the page via props
return { props: { data } }
}
export default Page
xxxxxxxxxx
export async function getStaticPaths() {
const res = await fetch(`${baseUrl}/wp-json/wp/v2/posts`)
const posts = await res.json()
//paths is array of objects which is contains one params property with id or slug
const paths = posts.map(({ slug }) => ({ params: { slug: `${slug}` } }))
return {
paths,
//fallback true mean there is no slug in build time then it will not shown 404 error
// and fetch data from server and show it
fallback: true,
}
}
xxxxxxxxxx
import type { InferGetServerSidePropsType, GetServerSideProps } from 'next'
type Repo = {
name: string
stargazers_count: number
}
export const getServerSideProps: GetServerSideProps<{
repo: Repo
}> = async () => {
const res = await fetch('https://api.github.com/repos/vercel/next.js')
const repo = await res.json()
return { props: { repo } }
}
export default function Page({
repo,
}: InferGetServerSidePropsType<typeof getServerSideProps>) {
return repo.stargazers_count
}
xxxxxxxxxx
getServerSideProps
/*getServerSideProps, is used to pre-render pages on each
request. When you use getServerSideProps in a page, Next.js will fetch the
necessary data on each request and then generate the HTML for that page on
the server before serving it to the client. This means that the page will
always have the most up-to-date data, but it may take longer to load because
it needs to fetch the data on each request.
*/
xxxxxxxxxx
You cannot use getServerSideProps in non-page components. You can either pass the prop from Home to HomeSection or create a context so the value can be available globally from the component tree
getServerSideProps can only be exported from a page. You can’t export it from non-page files.
https://nextjs.org/docs/basic-features/data-fetching#only-allowed-in-a-page-2