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)
@kachkaev here’s a workaround…
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 insiderenderas expected (in fact, same as the example Next.JS+Apollo code). So ingetInitialPropsI don’t have access to the [empty] data yet in order to return a 404 throughres.My current workaround is pretty gross:
I ended up doing something like this (don’t know if it’s an anti-pattern):
This way I can figure out the
statusCodein render time. It doesn’t require me to prefetch all my data ingetInitialPropsto decide thestatusCode(I’m using Apollo as well):Let me know what you guys think…
I’ve published
next-server-context, a way to access and even modify the server context via auseServerContext()hook: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: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
useGetCookieimplementation 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?Outlined a solution here: https://spectrum.chat/next-js/general/error-handling-in-async-getinitialprops~99400c6c-0da8-4de5-aecd-2ecf122e8ad0?m=MTUzOTUyMTA1OTE0Mw==
I’m resolve this problem that:
pages/[...404].tsxThrowing 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
@andreyvital Doing the same, I have also implemented the
<Redirect />component this way.For the lazy ones of you, I wrote a
withErrorHoC a week ago: https://www.npmjs.com/package/next-with-errorFeedback 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: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
Errorwith code set asENOENTyou can re-set HTTP status code back to 404 ingetInitialPropsright in custom_error.jspage