Created
June 14, 2019 12:08
-
-
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)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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