As title mentioned, how can I redirect client to 404 in getInitialProps()
?
for example, I cannot fetch results from API then the page should display "Not Found".
There is no way to render the default error page in this situation, but you can do the following for now.
static getInitialProps({ res }) {
if (res) {
res.statusCode = 404
res.end('Not found')
return
}
}
I'd really like to be able to do this.
How are you running this on zeit.co/blog
currently?
@nkzawa This seems cannot render the 404 page?
My current workaround which is working well for now:
import Error from './_error';
class Example extends Component {
static async getInitialProps({ res }) {
const data = await fetchSomeData();
if (!data && res) res.statusCode = 404;
return { data };
}
render() {
const { data } = this.props;
if (!data) return <Error status={404} />;
return <div>data: {data}</div>;
}
}
Best solution:
server.js
const express = require('express')
const next = require('next')
const dev = process.env.NODE_ENV !== 'production'
const app = next({ dev })
const handle = app.getRequestHandler()
app.prepare()
.then(() => {
const server = express()
server.get('/post/:slug', (req, res) => {
return app.render(req, res, '/post')
})
server.get('*', (req, res) => {
return handle(req, res)
})
server.listen(3000, (err) => {
if (err) throw err
console.log('> Ready on http://localhost:3000')
})
})
pages/post.js
const posts = [
{ slug: 'hello-world', title: 'Hello world' },
{ slug: 'another-blog-post', title: 'Another blog post' }
]
const Page = ({ post: { title } }) => (
<div>{title}</div>
)
Page.getInitialProps = async ({ req: { params: { slug } } }) => {
const post = posts.find(post => post.slug === slug)
if (!post) {
const err = new Error()
err.code = 'ENOENT'
throw err
}
return { post }
}
export default Page
@dizlexik Very useful, thanks!
Just a note: you have to pass the prop statusCode
to error, not status
. Updated code:
import Error from './_error';
class Example extends Component {
static async getInitialProps({ res }) {
const data = await fetchSomeData();
if (!data && res) res.statusCode = 404;
return { data };
}
render() {
const { data } = this.props;
if (!data) return <Error statusCode={404} />;
return <div>data: {data}</div>;
}
}
@dizlexik @nwshane Where is './_error'
coming from?
Did you have to create a custom error page?
@moroshko in his case yeah. But you can also use next/error
which is the build in error page 馃憤
This thread has been automatically locked because it has not had recent activity. Please open a new issue for related bugs and link to relevant comments in this thread.
Most helpful comment
My current workaround which is working well for now: