next.js: Way to return 404 http error code in render()

Is your feature request related to a problem? Please describe. Right now you can return 404 http error code only in getInitialProps, which is not nice, since you have to fetch the data twice. Once in getInitialProps to return the right http response code and once in the component itself when using apollo, so you will have loading property etc.

Describe the solution you’d like With react-router-dom you can have a component like this:

import React from 'react';
import { Route } from 'react-router-dom';

const NotFound = () => {
  return (
    <Route render={({ staticContext }) => {
      if (staticContext) {
        staticContext.status = 404;
      }
      return (
        <div>
          <h1>404 : Not Found</h1>
        </div>
      )
    }}/>
  );
};

export default NotFound;

With this component, you can simply have your apollo HOC near the components and SSR returns the correct http codes without the need for getInitialProps.

It would be great to be able to return http codes from render()

About this issue

  • Original URL
  • State: closed
  • Created 8 years ago
  • Reactions: 11
  • Comments: 23 (12 by maintainers)

Most upvoted comments

@kachkaev here’s a workaround…

import Error from 'next/error'

export const throw404 = () => {
  if (process.browser) {
    return <Error statusCode={404} />
  }
  const e = new Error()
  e.code = 'ENOENT'
  throw e
}

Similar use-case – I use Apollo for GraphQL and I would like to return a 404 on server renders where the result of a query is (for instance) empty.

My <Query> lives inside render as expected (in fact, same as the example Next.JS+Apollo code). So in getInitialProps I don’t have access to the [empty] data yet in order to return a 404 through res.

My current workaround is pretty gross:

<Query query={getResponses} variables={{ foo: this.props.bar }}>
  {({ loading, error, data }) => {
    // Check for error, loading etc.
    const responses = data.allResponses.nodes;
    if (responses.length === 0) {
      const e = new Error("Response not found");
      e.code = "ENOENT";  // Triggers a 404
      throw e;
    }

I ended up doing something like this (don’t know if it’s an anti-pattern):

// lib/ServerResponseContext.js
import { createContext } from "react";

export default createContext(null);

// lib/withServerResponse.js
import PropTypes from "prop-types";
import React from "react";
import ServerResponseContext from "./ServerResponseContext";

export default App => {
  return class extends React.Component {
    static displayName = "withServerResponse(App)";

    static propTypes = {
      response: PropTypes.func
    };

    static defaultProps = {
      response: () => null
    };

    static async getInitialProps(context) {
      const { ctx } = context;
      let props = {};

      if (App.getInitialProps) {
        props = await App.getInitialProps(context);
      }

      return {
        ...props,
        response: () => ctx.res
      };
    }

    render() {
      const { response, ...props } = this.props;

      if (process.browser) {
        return <App {...props} />;
      }

      return (
        <ServerResponseContext.Provider value={response()}>
          <App {...props} />
        </ServerResponseContext.Provider>
      );
    }
  };
};

// lib/StatusCode.js
import PropTypes from "prop-types";
import React from "react";
import ServerResponseContext from "./ServerResponseContext";

export default function StatusCode({ statusCode, children }) {
  if (process.browser) {
    return null;
  }

  return (
    <ServerResponseContext.Consumer>
      {response => {
        response.statusCode = statusCode;
        return children;
      }}
    </ServerResponseContext.Consumer>
  );
}

StatusCode.propTypes = {
  statusCode: PropTypes.number.isRequired,
  children: PropTypes.any
};

StatusCode.defaultProps = {
  children: null
};

This way I can figure out the statusCode in render time. It doesn’t require me to prefetch all my data in getInitialProps to decide the statusCode (I’m using Apollo as well):

<Query
  query={gql`
    ...
  `}
>
  {({ loading, data }) => {
    if (loading) {
      return <div>Loading...</div>;
    } else if (!data.user) {
      return (
        <>
          <StatusCode statusCode={404} />
          <div>Not found...🤔</div>
        </>
      );
    }

    return (
      <div>...</div>
    )
  }}
</Query>

Let me know what you guys think…

I’ve published next-server-context, a way to access and even modify the server context via a useServerContext() hook:

import { useServerContext } from 'next-server-context'

export default function ErrorMissing() {
  serverContext = useServerContext()
  if (serverContext) serverContext.response.statusCode = 404
  return (
    <section>
      <h1>Error 404</h1>
      <p>Something is missing.</p>
    </section>
  )
}

This, in combination with next-graphql-react (which can SSR GraphQL errors, unlike Apollo) allows you to have proper HTTP status codes for 403, 404, etc.

Examples:

This hook is very useful for creating other hooks, like useGetCookie() which allows you to isomorphically retrieve the cookie within component render:

import { useServerContext } from 'next-server-context'

export const useGetCookie = () => {
  const serverContext = useServerContext()
  return function getCookie() {
    return typeof window === 'undefined'
      ? serverContext
        ? serverContext.request.headers.cookie
        : undefined
      : document.cookie
  }
}

The way useServerContext() is implemented does not cause any data to be serialized on the server for hydration on the client.

Edit (5 Nov 2020): You might need a smarter useGetCookie implementation than the above example, if there is a chance that the cookie is being set in the response. Then you need to merge the request and response cookies.

This solution stoped working for me with the 9.2.2 upgrade (getting a 500 error when calling new Error(). Anyone noticing the same?

I’m resolve this problem that:

pages/[...404].tsx

import { GetServerSidePropsContext } from 'next'

export function getServerSideProps(context: GetServerSidePropsContext) {
  context.res.statusCode = 404;
  return {
    props: {
      someProp: 'some_value'
    }
  };
}

export default function Page404() {
  return (
    <h1>Page 404</h1>
  );
}

Looks like a breaking change 🤔

Throwing errors that magically turn into 404 is not a Next.js feature.

I’ve outlined many times how to correctly render 404: https://github.com/zeit/next.js/issues/4452#issuecomment-450642052

@dsds191919 here’s something that works

import React, {FunctionComponent} from "react";
import NextError from 'next/error'

interface ErrCodeException extends Error {
    code?: string;
}

const Throw404: FunctionComponent<{}> = () => {
  if (process.browser) {
    return <NextError statusCode={404} />
  }

  const e = new Error() as ErrCodeException
  e.code = 'ENOENT'
  throw e;
}

export default Throw404;

@andreyvital Doing the same, I have also implemented the <Redirect /> component this way.

For the lazy ones of you, I wrote a withError HoC a week ago: https://www.npmjs.com/package/next-with-error

Feedback is appreciated 😃

@shauns thanks for sharing this trick with e.code = "ENOENT" – it works for me when the page is rendered on the server. How would you achieve the same behaviour with client-side rendering? E.g. when a person clicks on a product in a list, but it has just been deleted. At the moment, I see this instead of my usual 404 page:

screen shot 2018-06-02 at 11 09 00

Refreshing the page shows a proper 404 error page, but that’s because Apollo fetching is done on the server this time.

When you throw Error with code set as ENOENT you can re-set HTTP status code back to 404 in getInitialProps right in custom _error.js page

Error.getInitialProps = async ({ err, res }) => {
  if (err?.code === 'ENOENT') {
    res.statusCode = 404;
  }
}