Additional keys were returned from `getServerSideProps`. Return notFound object from getServerSideProps

Viewed 5527

I have next app. I need to realize logic when route is not match in [slug] page then show 404 page error.

In next as far as I know for show 404 page I need to return notFound object with value true.Link

So the question is when I return { notFound: true } from getServerSideProps why I get this error?

Error: Additional keys were returned from getServerSideProps. Properties intended for your component must be nested under the props key, e.g.:

return { props: { title: 'My Title', content: '...' } }

Keys that need to be moved: notFound.

Code:

export const getServerSideProps: GetServerSideProps = async ({ params, req }) => {

    const { slug } =  params;

    // first request
    const data = await (await fetch(`${process.env.NEXT_PUBLIC_API_HOST}/${slug}`)).json();

    // second request
    const user = await fetch(`${process.env.NEXT_PUBLIC_API_HOST}`, {
        method: "GET",
        headers: {
            'Authorization': 'Bearer ' + "jwt",
            'Content-Type': 'application/json',
        },
    });
    const userInfo = await user.json();


    if ( !slug || data.statusCode === 404 ) return { notFound: true }

    return {
        props: {
            title: "something",
            // my props in here
        },
    }
}

It gives error only when I write something in url and change my slug page consciously from correct to incorrect. For example from localhost/page/1 to localhost/page/blablabla.

In this case when I change route to wrong works this if case (if ( !slug || data.statusCode === 404 ) ).Next version 9.5.2

1 Answers

You are using Next version 9.5.2. The earliest version that supports notFound is 10.0.0. From the docs:

>v10.0.0 locale, locales, defaultLocale, and notFound options added.

So you have to upgrade to use that logic.

Related