getServerSidePropsis a Next.js function that can be used to fetch data and render the contents of a page at request time.
Here a example shows how can yout fetch a data in API and pass de data to page as a props
import type { InferGetServerSidePropsType, GetServerSideProps } from 'next'
type Repo = {
name: string
stargazers_count: number
}
export const getServerSideProps = (async () => {
// Fetch data from external API
const res = await fetch('<https://api.github.com/repos/vercel/next.js>')
const repo: Repo = await res.json()
// Pass data to the page via props
return { props: { repo } }
}) satisfies GetServerSideProps<{ repo: Repo }>
export default function Page({
repo,
}: InferGetServerSidePropsType<typeof getServerSideProps>) {
return (
<main>
<p>{repo.stargazers_count}</p>
</main>
)
}
dynamic data, when i need a data return every request make for the user, like a social media or a admin dashboard.
Acess to variables session and request, when i do a login example, and generate a session key, and when i acess other page and a i need this session key to authentication in aplication, this verification a occurs in server.
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 bygetStaticProps.
import type { InferGetStaticPropsType, GetStaticProps } from 'next'
type Repo = {
name: string
stargazers_count: number
}
export const getStaticProps = (async (context) => {
const res = await fetch('<https://api.github.com/repos/vercel/next.js>')
const repo = await res.json()
return { props: { repo } }
}) satisfies GetStaticProps<{
repo: Repo
}>
export default function Page({
repo,
}: InferGetStaticPropsType<typeof getStaticProps>) {
return repo.stargazers_count
}