Professional Documents
Culture Documents
—> in traditional react apps, the data is loaded into html after the page is loaded. Initially the html code is empty ==> bad for SEO, users may have to wait
—> in NEXT.JS after the request is made, the user will receive a pre-rendered page that comes with javascript that makes the app interactive
—> in next.js there are 2 types of pre-rendering (static generation or server-side rendering)
I. Static generation
—> pre-generates a page during the build time, before deployment
—> once they are deployed, the pre-built pages are cached by the server ==> the server can serve the pages instantly
—> the code that we want to be pre-generated is written inside every component in the getStaticProps async function
—> the code written in this function is not included in the bundle
—> inside the getStaticProps we can write server side code ==> we can access the memory etc.
—> the getStaticProps takes an argument named context that has proprieties like the path, where we can access the dynamic params.
ex:
—> Bc. the function is executed during build time and it isn’t included in the code bundle, we can access the file system.
EX:
function HomePage(props) {
const { products } = props;
console.log(products);
return (
<ul>
{products.map((product) => (
<li key={product.id}>{product.title}</li>
))}
</ul>
);
}
export async function getStaticProps() {
const filePath = path.join(process.cwd(), "data", "dummy-backend.json");
const jsonData = await fs.readFile(filePath);
const data = JSON.parse(jsonData);
return {
props: {
products: data.products,
},
};
}
—> bc. we use static generation, if we update the data, we have to rebuild the entire project
—> to implement ISR we have to add in the returned object the revalidate key which its value is the number of seconds the page has to be re-rendered.
return {
props: {
products: data.products,
},
revalidate: 10,
};
notFound - a boolean property. if is set to true the user will be redirected to the 404 page
return {
notFound: true
};
return {
redirect: {
destination: "no-data",
}
}
Pre-generated paths:
—> if we have a dynamic path (the name is in between the []) we cannot use the getStaticProps function singly
—> we have to use the getStaticPaths function where we have to tell NEXT.JS for which specific arguments the pages will be re-rendered
ex:
—> if we set the fallback to true, it means that the values that are not set there, are still generated but when the request is made
—> the dynamic generation is not made immediately ==>we have to set a loading state.
—> if we set the fallback to blocking, the server will wait until the page is fully loaded ==> we do not need a loading state
—> the return obj of the getServerSideProps can have the same props. as the getStaticProps expect the revalidate prop.
—> the context (argument of the getServerSideProps function) has access to the request made to the server, to the response sent back and to the params.