Skip to content

Instantly share code, notes, and snippets.

@martpie
Created June 14, 2019 12:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save martpie/a79dc33343f650941c388708d9f5e38b to your computer and use it in GitHub Desktop.
Save martpie/a79dc33343f650941c388708d9f5e38b to your computer and use it in GitHub Desktop.
Return a 404 from a Next.js page render method (ssr + client-side)
import React from 'react';
import ErrorPage from 'next/error';
// Allow to render the error page + return the correct error code with SSR
// It is a hack and has the disadvantage of logging this server-side
// https://github.com/zeit/next.js/issues/4451
// A better solution is welcome.
export const render404Error = () => {
if (process.browser) {
return <ErrorPage statusCode={404} />;
}
const error = new Error('404 triggered');
// @ts-ignore necessary to return a 404
// https://github.com/zeit/next.js/issues/3452#issuecomment-436749130
error.code = 'ENOENT';
throw error;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment