#SSR components
1 messages · Page 1 of 1 (latest)
To force server rendering of a component in Next.js, you can use the getServerSideProps function. This function allows you to fetch data on each request, which is useful when you want to render data that changes often.
Here's an example of how you can use getServerSideProps:
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
}
In this example, getServerSideProps fetches data from an API and passes it to the Page component. The data is fetched on each request, ensuring that the most current data is always rendered.
Remember, any props returned by getServerSideProps will be passed to the page component and can be viewed on the client-side in the initial HTML. This is to allow the page to be hydrated (https://react.dev/reference/react-dom/hydrate) correctly. Make sure that you don't pass any sensitive information that shouldn't be available on the client in props.
For more information, you can check out the Next.js documentation on Data Fetching (https://nextjs.org/docs/pages/building-your-application/data-fetching) and Server-side Rendering (https://nextjs.org/docs/pages/building-your-application/rendering/server-side-rendering).
Note: you can ask me a follow up question by @ mentioning me again :speech_balloon:
@muted oar kapa.ai is still learning and improving, please let us know how it did by reacting below
Im talking about nextJs13 with app dir approach. There is no "getServerSideProps"
@placid fjord Im talking about nextJs13 with app dir approach. There is no "getServerSideProps"
Let me check the knowledge base for you. One moment! :books:
In Next.js 13 with the new app directory approach, you can use the fetch API to fetch data on the server side. You can control the caching behavior of the fetch request by setting the cache option in the fetch options.
To fetch data on every request, similar to getServerSideProps, you can set the cache option to no-store. This will ensure that the fetched data is not cached and is fetched anew on every request.
Here's an example:
fetch(URL, { cache: 'no-store' });
In this example, URL is the URL of the resource you want to fetch. The { cache: 'no-store' } option tells the browser that the fetched data should never be cached.
This approach allows you to colocate your data fetching inside your React components, which can lead to less JavaScript being sent to the client and maintaining the rendered HTML from the server.