Skip to main content

Posts

Showing posts from April, 2023

NextJs Error - Invalid Redirect getStaticProps/getServerSideProps

  Both getStaticProps and getServerSideProps usually returns props but both functions can also return "redirect" object. Redirect object is used to redirect the user to a different url.  Invalid Redirect getStaticProps/getServerSideProps error occurs when redirect object that was returned did not have correct structure . To fix the issue make sure the redirect object holds proper values in correct shape  { destination: string, permanent: boolean } . destination requires a url path in string example "/" . permanent requries a boolean value. You can instead use statusCode can also be used but not both together . statusCode requires a number values . This would represent the status code . export async function getStaticProps() { const data = null; // since data is to null if condition will be validated & redirect will occur if (!data) { return { redirect: { destination: "/", permanent: false, // statusCode: 3...

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 - Your `getServerSideProps` function did not return an object. Did you forget to add a `return`?

  When a page component makes use getServerSideProps function and does not return a valid props object then this error will be thrown on to the console . To fix the error make sure to always have a return statement which returns an object {props:{oof:"oof"}} 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 { props: { yourObjectKey: anyValidData , yourObjectKey2: anyValidData2 } } } You might also encounter other errors when using the getServerSideProps : ` undefined` cannot be serialized as JSON. Please use `null` or omit this value. Invalid getServerSideProps Return Value You can not use getStaticProps with getServerSideProps. To use SSG, please remove getServerSideProps

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 - You can not use getInitialProps with getStaticProps. To use SSG, please remove your getInitialProps

This error was widely noticed when codebase gets upgraded to React 18 / latest versions of Nextjs. If you are using newer versions of Nextjs , then it is better to use getStaticProps instead of getInitialProps . Do not mix both together , either use getStaticProps or getInitialProps . getStaticProps - when used on page leads to static site generation (SSG) getServerSideProps - when used on page leads to server side rendering (SSR) & only available on page components . You might also encounter other errors when using nextjs: ` undefined` cannot be serialized as JSON. Please use `null` or omit this value. Your `getServerSideProps` function did not return an object. Did you forget to add a `return`? You can not use getStaticProps with getServerSideProps. To use SSG, please remove getServerSideProps

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