-
Notifications
You must be signed in to change notification settings - Fork 27.6k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Redirect to 404 page in getInitialProps()? #746
Comments
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 |
@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
|
@moroshko in his case yeah. But you can also use |
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. |
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".
The text was updated successfully, but these errors were encountered: