Skip to main content

Posts

Showing posts with the label ssr

Data Fetching Made Easy: Exploring Different Data Fetching Techniques in Next.js

Fetching data from external APIs or databases is often the backbone of modern web applications. Next.js, being a versatile framework, provides various mechanisms for fetching and handling data seamlessly, empowering you to build dynamic and interactive user experiences. In this blog post, we'll delve into the different data fetching techniques available in Next.js, along with practical code examples and insights to guide you in choosing the right approach for your specific needs. Fundamental Approaches: getStaticProps and getServerSideProps At the heart of data fetching in Next.js lie two crucial functions: getStaticProps and getServerSideProps. These functions enable you to fetch data at different stages of the rendering process, offering varying advantages depending on your application's requirements. 1. getStaticProps: Pre-rendering Paradise The getStaticProps function shines when you aim for pre-rendering your pages, meaning the content is generated during build time a...

Next.js Lazy Load: Optimizing Performance for React Applications

 Next.js Lazy Load is a built-in feature that allows you to defer the loading of components until they are actually needed, improving the initial load time and overall performance of your Next.js application. How it Works Next.js Lazy Load utilizes dynamic imports to load components only when they are about to be rendered. This is achieved through the next/dynamic function, which creates a dynamic import that is resolved at runtime. Benefits Faster initial load: By only loading necessary components, Next.js Lazy Load reduces the initial bundle size, resulting in a faster load time for your application. Improved memory management: Since components are only loaded when needed, Next.js Lazy Load helps prevent memory leaks and keeps your application running smoothly. Enhanced user experience: Faster load times and improved performance lead to a more responsive and satisfying user experience. Implementation Implementing Next.js Lazy Load is straightforward: import dynamic from 'next/dyn...

Type error: 'GetServerSideProps' refers to a value, but is being used as a type here. Did you mean 'typeof GetServerSideProps'

Type error: 'GetServerSideProps' refers to a value, but is being used as a type here. Did you mean 'typeof GetServerSideProps' This error occurs when you use imported "GetServerSideProps" server side props function . "GetServerSideProps" is the typescript type of "getServerSideProps". To fix the error : If you are using javascript then just remove the import GetServerSideProps from "next" and then change the server side function to: export const getServersideProps = async () => {   return { props: { oof: "hello" } }; }; If codebase is typescript based then use "GetServerSideProps" as the type and modify the function to : export const getServerSideProps: GetServerSideProps = async () => {   return { props: { oof: "hello" } }; }; You might also encounter other errors when using the getServerSideProps : ` undefined` cannot be serialized as JSON. Please use `null` or omit this val...

NextJs Error - You can not use getStaticProps with getServerSideProps. To use SSG, please remove getServerSideProps

  When page uses getServerSideProps nextjs will try to server side render the page . That is getServerSideProps  executes api fetch calls to get data & feed into the page and return the page html (all this is done on the server side). getServerSideProps  gets triggered "at request time" aka when someone (browser) requests a page which has been marked as SSR . It gets triggered on each request. getStaticPaths gets triggered "at build time" aka when the next build command is used. Pages which uses getStaticPaths gets data from the motioned sources and creates static html pages. To fix issue first decide whether the current page should be a static html page ! If the answer is yes then remove the getServerSideProps and keep using getStaticProps . This will make the current page static html page. If  the answer is no then remove the getStaticProps and keep using getServerSideProps . This will make the current page to be server side rendered ...

NextJs Error - Invalid getServerSideProps Return Value

This error caused inside getServerSideProps code block when the props return values does not follow the required structure . The return value should have a "props" as key and then {"propertytKeyAsString":anyValidData }. Here: "propertytKeyAsString" - the key (name) you assign for the property. This will be de-structured to get property value inside the page component . "anyValidData" includes any valid data type that can be assigned  , it could be number , string , boolean, array , objects & null . Caution do not try to pass values of "undefined" data type , this will cause a different error . To fix Invalid getServerSideProps Return Value  Follow the required props structure and return a valid data export async function getServerSideProps() { //anyValidData can be number , string , boolean , array , objects & null // but do not pass undefined // keep in mind these will be serialized (aka made into valid json ) return { ...

GetServerSideProps Inefficient internal api call - example & alternative

 GetServerSideProps at request time fetches data from api endpoints and renders a content on the page,  a pretty neat feature.  We directly make the api call within the getServerSideProps function block which gets executed at the server side (not the client side aka browser). External api endpoints are on different sever and the way to interact & get data from them is by making api call . But what if it is an internal api endpoint? Like the "localhost:3000/api/hello" api endpoint is being called in page path "localhost:3000/blog/is-there-a-better-way" . As you can see both things reside on "localhost:3000" Nextjs documentation calls this inefficient and instead actually execute the all required operations from the getServerSideProps code block https://nextjs.org/docs/basic-features/data-fetching/get-server-side-props#getserversideprops-or-api-routes // path path -> src/pages/blog/alternative export default function InternalApiTest({ data }) { ...

Server Error getServerSideProps - `undefined` cannot be serialized as JSON. Please use `null` or omit this value.

  Error : Error serializing `.oof` returned from `getServerSideProps` in "/oof". Reason: `undefined` cannot be serialized as JSON. Please use `null` or omit this value. You got this error while using getServerSideProps . Everything is working but not able to pass the values to props. Few things to note before proceeding forward: this is a server side error , meaning you have problematic code executed on the server side inside getServerSideProps . current content cannot be serialized as json (aka make it into a valid json format ) .  this could be because of date object , "undefined" , etc. The above screenshot contains getServerSideProps code block which caused the error. The oof variable was set to "undefined" intentionally to cause the error but you might encounter this error while using url params or other situations . If you face this error check what data is being passed and if undefined be passed make sure to set it as "null" instead . Rea...

GetServerSideProps(context) - Example - NextJs

 GetServerSideProps(context) - NextJs example GetServerSideProps is executed in the server side but what if we want to access the resolved url , params or query attached to the url ? This is when "context" parameter of getServerSideProps is used .  Context is an object so we de-structure the items we want like the usual way. It contains several useful values: query - with this we can get the queries attached to current url . Example - "localhost:3000/?search="oof"" , using the context we can access the query ({search:"oof"}) from the server side & execute operations. (note: query object can also hold the param value if it exists.) params - get the params data if it exists on server side. The params would still follow the dynamic route set key name . For example if a dynamic route page like "pages/post/[id].js" , the param would be stored as {id:1}.(like the useRouter) resolvedUrl - stripped down version of requested url with paths ...

GetServerSideProps Code Example - NextJS

 GetServerSideProps Example NextJs GetServerSideProps when used in Nextjs several things happen - Code placed within this function gets run only on the serverside  Getserversideprops is run before the Page Component (note: this can used only on Page level) The page which contains this function would be Server Side Rendered (SSR - this would be marked with ssr symbol in the build production logs) Frontend does not have access this function, so business logic can be placed here. Code example: /** * * @param {*} jsonData * * This is the page component. * Remember getServerSideProps can only be used on Page level! * * */ export default async function Home ({ jsonData }) { // destructured jsonData which was passed from gerserversideprops // note this is in JSON , so make sure to parse it console.log(jsonData, "data"); // parsing the json data - with this we have a workable object (it could be any array , object, arary of objects & so on) ...

Topics

Show more