Next.js getServerSideProps always undefined

Asked
Active3 hr before
Viewed126 times

9 Answers

undefinedgetserversidepropsalways
90%

Make sure that is a Next.js page and located in pages directory as getServerSideProps only allowed in a page., Meta Stack Overflow , Outdated Answers: results from flagging exercise and next steps

Nothing wrong with the code but it could be in a wrong place.

/n

Make sure that is a Next.js page and located in pages directory as getServerSideProps only allowed in a page.

pages

Nothing wrong with the code but it could be in a wrong place.

/n

Make sure that is a Next.js page and located in pages directory as getServerSideProps only allowed in a page.

getServerSideProps
load more v
88%

In case you added _app.js file into your project according official documentation you need add Component and pageProps inside, here is a minimal implementation of _app.js file.

function MyApp({ Component, pageProps }) {
   return <Component {...pageProps} />
}

export default MyApp
load more v
72%

Working on trying to use getServerSideProps in a page [slug].tsx and in the function, the data is defined and can console log it and see the data, however in the actual page if I try and output that data its always undefined and props seems to be just {}. I'm not sure if my syntax is wrong here or if there is something deeper going on.,The issue in here. Because, pageProps object is empty object and probably it override the original one.,Make sure you are not using getServerSideProps inside a component, it can only be used in the top-level page in /pages

import ReactMarkdown from 'react-markdown';
import Link from 'next/link';
import Card from '../../components/Card';
import { FullArticle } from '../../components/articles/Full';
import { NextPage, GetServerSideProps } from 'next';
import { Layout } from '../../components/layout/PageLayout';

// @ts-ignore
const PostPage: NextPage = ({data}) => {
  console.log(data); // outputs undefined

  if (data !== undefined) {
    if (data.articles.length >= 1) {
      return (
        <Layout meta={{title, description, useSEO: false}}>
          // @ts-ignore
          {data !== undefined && data.articles.map(article => (
              <FullArticle article={article}>
                <ReactMarkdown source={article.content} escapeHtml={false} />
              </FullArticle>
            ))}
        </Layout>
      );
    }
  }
};

export const getServerSideProps: GetServerSideProps = async context =>  {
  const { slug } = context.query;

  const response = await fetch(url);
  const data = await response.json();
  return { props: { data }}

}

export default PostPage;
load more v
65%

The signature is { Component, pageProps }, you're using { Component, props } so the page props are not being passed into the component, hence why you're not seeing the getServerSideProps result.,As described in the documentation, the results returned from getServersideProps is undefined.,Getting the same issue. Very strange. I've added getServerSideProps into my CarTab.tsx inside page (car/[id].tsx) and it's always undefined. I've even created an index.tsx inside car/ and it's still undefined. Is this an issue with Next or am I missing something really obvious? Thanks all

import React from 'react';
import { GetServerSideProps, InferGetServerSidePropsType } from 'next';

export const getServerSideProps: GetServerSideProps = async () => {
	return {
		props: {
			results: [1,2,3],
		},
	};
};

function Page({results}: InferGetServerSidePropsType<typeof getServerSideProps>) {
	console.log(results) // undefined
	return (
		<div className="app__page header">page here</div>
	)
}

export default Page;
load more v
75%

 Pretag team - issue, fix, solve, resolve
40%

I'm using nextjs 9.3.5 and even the simplest example of getServerSideProps is always failing:,This is basically a cut and paste from the very simple example on the nextjs website. getInitialProps works fine. ,If you add any files,it will delete all existing files related to this question-(questions only answer remains unchanged)

I'm using nextjs 9.3.5 and even the simplest example of getServerSideProps is always failing:

function Page({ data })
{
    //Prints undefined
    console.log(data);

    return <div>Data in props: {data}</div>
}

export async function getServerSideProps()
{
    var data = "Hello";

    //Prints "Hello"
    console.log(data);

    return { props: { data } };
}

export default Page
load more v
22%

getServerSideProps (Server-side Rendering): Fetch data on each request.,preview is true if the page is in the preview mode and undefined otherwise. See the Preview Mode documentation.,preview: preview is true if the page is in the preview mode and false otherwise. See the Preview Mode documentation.

notFound - An optional boolean value to allow the page to return a 404 status and page. Below is an example of how it works:

export async function getStaticProps(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
   }
}
load more v
60%

Shallow routing allows you to change the URL without running data fetching methods again, that includes getServerSideProps, getStaticProps, and getInitialProps.,To enable shallow routing, set the shallow option to true. Consider the following example:,The URL will get updated to /?counter=10. and the page won't get replaced, only the state of the route is changed.

To enable shallow routing, set the shallow option to true. Consider the following example:

import {
   useEffect
} from 'react'
import {
   useRouter
} from 'next/router'

// Current URL is '/'
function Page() {
   const router = useRouter()

   useEffect(() => {
      // Always do navigations after the first render
      router.push('/?counter=10', undefined, {
         shallow: true
      })
   }, [])

   useEffect(() => {
      // The counter changed!
   }, [router.query.counter])
}

export default Page
load more v
48%

In the line below, if I print initialState it is always null; therefore, the cache is not populated to the client side apollo. https://github.com/vercel/next.js/blob/19f3306aaadc00be1ba6d3521dfdeca49d7a95fe/examples/api-routes-apollo-server-and-client/apollo/client.js#L32-L36,When I print apolloClient.cache.extract() I am getting a correct cache value; however, this is not passed on to initialState in the initializeApollo function.,What should I do in order to have the SSR apollo cache populate the Client Side apollo cache?

My client.tsx file looks like below

import fetch from "isomorphic-unfetch";

let apolloClient;

function createIsomorphLink() {
   let uri;

   if (typeof window == 'undefined') {
      uri = CONFIG.apolloServerSideUrl;
   } else {
      uri = CONFIG.apolloClientSideUrl;
   }

   return new HttpLink({
      fetch: fetch,
      uri: uri,
      credentials: 'same-origin',
   });
}

function createApolloClient() {
   return new ApolloClient({
      ssrMode: typeof window === 'undefined',
      link: createIsomorphLink(),
      cache: new InMemoryCache(),
   })
}

export function initializeApollo(initialState = null) {
   const _apolloClient = apolloClient ?? createApolloClient();

   // If your page has Next.js data fetching methods that use Apollo Client, the initial state
   // get hydrated here
   console.log('initial state');
   console.log(initialState);
   if (initialState) {
      _apolloClient.cache.restore(initialState);
   }
   // For SSG and SSR always create a new Apollo Client
   if (typeof window === 'undefined') return _apolloClient;
   // Create the Apollo Client once in the client
   if (!apolloClient) apolloClient = _apolloClient;

   return _apolloClient
}

export function useApollo(initialState) {
   const store = useMemo(() => initializeApollo(initialState), [initialState])
   return store
}
load more v

Other "undefined-getserversideprops" queries related to "Next.js getServerSideProps always undefined"