Next.js: Redirect to 404 page in getInitialProps()?

Created on 12 Jan 2017  路  9Comments  路  Source: vercel/next.js

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".

bug

Most helpful comment

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>;
  }
}

All 9 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 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.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

knipferrc picture knipferrc  路  3Comments

olifante picture olifante  路  3Comments

formula349 picture formula349  路  3Comments

lixiaoyan picture lixiaoyan  路  3Comments

ghost picture ghost  路  3Comments