getServerSideProps
Bir sayfadan getServerSideProps
(Server-Side Rendering) adlı bir işlev dışa aktarıldığında Next.js, getServerSideProps
tarafından döndürülen verileri kullanarak her istekte bu sayfayı önceden oluşturacaktır. Bu, sık sık değişen verileri almak ve sayfanın en güncel verileri gösterecek şekilde güncellenmesini istiyorsanız kullanışlıdır.
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>
)
}
getServerSideProps
adresinde kullanmak üzere modülleri üst düzey kapsamda içe aktarabilirsiniz. Kullanılan içe aktarmalar istemci tarafı için paketlenmeyecektir. Bu, veritabanınızdan veri almak da dahil olmak üzere sunucu tarafı kodunu doğrudan getServerSideProps
adresinde yazabileceğiniz anlamına gelir.
Context parameter
context
parametresi aşağıdaki anahtarları içeren bir nesnedir:
Name | Description |
---|---|
params | If this page uses a dynamic route, params contains the route parameters. If the page name is [id].js , then params will look like { id: ... } . |
req | The HTTP IncomingMessage object, with an additional cookies prop, which is an object with string keys mapping to string values of cookies. |
res | The HTTP response object. |
query | An object representing the query string, including dynamic route parameters. |
preview | (Deprecated for draftMode ) preview is true if the page is in the Preview Mode and false otherwise. |
previewData | (Deprecated for draftMode ) The preview data set by setPreviewData . |
draftMode | draftMode is true if the page is in the Draft Mode and false otherwise. |
resolvedUrl | A normalized version of the request URL that strips the _next/data prefix for client transitions and includes original query values. |
locale | Contains the active locale (if enabled). |
locales | Contains all supported locales (if enabled). |
defaultLocale | Contains the configured default locale (if enabled). |
getServerSideProps return values
getServerSideProps
işlevi, aşağıdaki özelliklerden herhangi birine sahip bir nesne döndürmelidir:
props
props
nesnesi, her bir değerin sayfa bileşeni tarafından alındığı bir anahtar-değer çiftidir. Serileştirilebilir bir nesne olmalıdır böylece aktarılan herhangi bir sahne aşağıdakilerle serileştirilebilir JSON.stringify
.
export async function getServerSideProps(context) {
return {
props: { message: `Next.js is awesome` }, // will be passed to the page component as props
}
}
notFound
notFound
boolean'ı sayfanın bir 404
durumu ve 404 Sayfası döndürmesini sağlar. notFound: true
ile, daha önce başarıyla oluşturulmuş bir sayfa olsa bile sayfa bir 404
döndürür. Bu, kullanıcı tarafından oluşturulan içeriğin yazarı tarafından kaldırılması gibi kullanım durumlarını desteklemek içindir.
export async function getServerSideProps(context) {
const res = await fetch(`https://.../data`)
const data = await res.json()
if (!data) {
return {
notFound: true,
}
}
return {
props: { data }, // will be passed to the page component as props
}
}
redirect
redirect
nesnesi dahili ve harici kaynaklara yönlendirmeye izin verir. { destination: string, permanent: boolean }
şekliyle eşleşmelidir. Bazı nadir durumlarda, eski HTTP
istemcilerinin düzgün şekilde yeniden yönlendirilmesi için özel bir durum kodu atamanız gerekebilir. Bu durumlarda, permanent
özelliği yerine statusCode
özelliğini kullanabilirsiniz, ancak ikisini birden kullanamazsınız.
export async function getServerSideProps(context) {
const res = await fetch(`https://.../data`)
const data = await res.json()
if (!data) {
return {
redirect: {
destination: '/',
permanent: false,
},
}
}
return {
props: {}, // will be passed to the page component as props
}
}
Version History
Version | Changes |
---|---|
v13.4.0 | App Router is now stable with simplified data fetching |
v10.0.0 | locale , locales , defaultLocale , and notFound options added. |
v9.3.0 | getServerSideProps introduced. |