next.js: Custom route `post/`id` flashing 404 before finally rendering page.

I’m currently experiencing a problem with my post/:id routes where next flashes the 404 page before successfully rendering my component. At first, I thought this was a redux related issues as my post/id pages are checking the app state to filter whichever component should be shown using shallow routing.

After discussing this in the slack channel, I added another API call that would retrieve each blog post but quickly found that I still encountered the same issue. I know that this has happened for at least one other developer so i’m wondering if anyone can point me in the right direction? I’m trying to finish up this personal portfolio I built with next.

Below, you can see exactly what’s happening. Everything looks A1 except for that 404 that blinks whenever a specific post is rendered.

next.js blog post err

The benefits i’ve gained are tremendous however there have been some minor issues like this one that have got me a little puzzled 🤔 . Anyways, let me know if I can provide any additional info. Thanks 😄

About this issue

  • Original URL
  • State: closed
  • Created 9 years ago
  • Reactions: 37
  • Comments: 49 (27 by maintainers)

Most upvoted comments

So to answer this one once and for all:

href => path inside of the pages directory + the querystring as => rendered in the browser url bar

Example:

You have a url called /products/:id

  1. You created pages/product.js
export default class extends React.Component {
  static async getInitialProps({query}) {
    console.log('SLUG', query.slug)
    return {}
  }
  render() {
    return <h1>The product page</h1>
  }
}
  1. You add the route to express or any other server, this is only for SSR. What this will do is route the url /products/:id to pages/product.js and provide id as part of query in getInitialProps:
server.get("/products/:slug", (req, res) => {
  return app.render(req, res, "/product", { slug: req.params.slug })
})
  1. For client side routing you use next/link like this:
<Link href="/product?slug=something" as="/products/something"> 

The reason you have to explicitly provide the href and as is that Next.js is not aware of any other pages on the client side. We don’t send a manifest of all pages to the client side and subsequent routes get lazy-loaded, which is scalable.

There is a community package that abstracts away providing href and as by sending a pre-defined manifest of all routes, note that we recommend not sending a full manifest of all possible routes as not doing this is more scaleable

https://github.com/fridays/next-routes

Also, note that rendering 404 is no longer the default behavior of Next.js. Instead, we reload the page for the Zones feature.

It’s not fixed.

I’m also getting 404 flashing without any custom routes. Just a file called orders.js in pages/ with this code:

import { Component } from 'react';

class Orders extends Component {
  render() {
    return (
      <div>
        <h2>My Orders</h2>
      </div>
    )
  }
}

export default Orders;

How are you rendering the Link component to that url? Are you using <Link href="/post/1"> or <Link href="/post?id=1" as="/post/1">?

@justinmchase I just had the same problem. Check Next Router documentation if you haven’t already.

You can use it as Router.push(url, as, options):

Router.push('/post/[pid]', '/post/abc')

This fixes the flashing 404 for me:

Link

<Link href="/somepage?id=value" as="/somepage/value">

Server side

server.get("/somepage/:id", (req, res) => {
  return app.render(req, res, "/maps", { id: req.params.id })
})

Access param on page

const { id } = this.props.url.query

The correct way to do what you outlined is to create pages/integration/[slug].js

And link to it in this way:

<Link href={`/integration/[slug]`} as={`/integration/${slug}`}>

How are you rendering the Link component to that url? Are you using <Link href="/post/1"> or <Link href="/post?id=1" as="/post/1">?

You should put this in doc. 😂

@sergiodxa

@tgrecojs I made an example repo https://github.com/sergiodxa/next-custom-query (deployed: https://next-custom-query.now.sh/blog), there you can see how to use the custom urls without reloading and a 404 using the next/link component as described above.

@sergiodxa I just put this code in place.

<Link href={`/blog?id=${x.id}`} as={`blog/${x.id}`}>
    <a>Read Post</a>
 </Link>

Now it’s re-rendering the /blog page on every click while adding the id to the URL.

url error gif

@Theo- the href in that next/link is user?id=1, can you try /user?id=1 instead? I think the 404 is because Next.js is trying to get to /current/path/user?id=1 instead of /user?id=1, but when the page reload it works fine because of the server render.

Seems like a pretty critical issue 😅

@timneutkens I would like to host my next.js app on ZEIT.now but that doesn’t have an option to run an express server. Do I loose my pretty urls now and can only do param=value&param=value or is there another way? The example Sergio posted doesn’t look promising

You don’t need a custom server for dynamic routes, see https://nextjs.org/docs/routing/dynamic-routes

I got the same issue before and I was able to solve it. I’m using an express server set up. I found out that the reason why the 404 page flashes before loading to the right page is because my page slug doesn’t match my component name.

When I have this code the 404 flashes:

server.get('/search', (req, res) => {
    const actualPage = '/search_results'
    const queryParams = { filters: req.query }
    app.render(req, res, actualPage, queryParams)
  })

Note that the /search and my actualPage values are different.

The 404 flashes disappears when I rename my component & the actualPage values to be the same as my page slug which is search. See working code below:

server.get('/search', (req, res) => {
    const actualPage = '/search'
    const queryParams = { filters: req.query }
    app.render(req, res, actualPage, queryParams)
  })

Now both are using /search.

Sorry for my english guys.

@moaxaca I have solved the same way since i was needed to have my own custom routing - i just disabled next’s one altogether.

I am having a similar problem and absolutely tearing my hair out over it!

In dev mode, I am getting a momentary runtime error when I click on a dynamic link. The error appears for a couple of seconds then the required page renders correctly. NB the error cannot be replicated in production.

Error

Unhandled Runtime Error
Error: Failed to load script: /_next/static/chunks/pages/%5BvenueId%5D/events/detail/%5Bdate%5D/%5BeventId%5D.js
Call Stack
appendScript/</script.onerror
node_modules/next/dist/client/route-loader.js (83:51)

Link

<Link
href={`/${venueId}/events/detail/${date}/slug=${eventId}`}
as={`/${venueId}/events/detail/${date}/${eventId}`}
>
<a className="font-bold text-lg">{name}</a>
</Link>

File Structure to page I am trying to reach: pages/[venueId]/events/detail/[…slug].tsx

The error persists if I attempt to replicate the file structure in my href. Same error with the code as follows:

href={`/${venueId}/events/detail/${eventId}`}
as={`/${cinemaId}/events/detail/${date}/${eventId}`}

The one thing that does get rid of the error is if I simply paste the template literal from the as prop in as the href and remove the ‘as’ prop:

href={`/${venueId}/events/detail/${date}/${eventId}`}

This renders the required page swiftly and flawlessly without error. BUT when I try to navigate ‘back’ to the previous page using the browser ‘back’ button, it changes the URL to the correct address for the previous page, but remains on the same page.

Hi can I ask why when i call this one

Router.push( '/about?id=1234','/about')

the id cant be retrieve, and the page i am using is […index].js which is a multi dynamic catch all page, but if I direct to other page that is not dynamic one it can work properly example car.js push to vehicle.js… Is there a better way where i can push to my dynamic catch all page and then mask the id and still able to retrieve it…?

I’m seeing this issue as well. @moaxaca’s solution didn’t work for me. What did was to use any Link component, but instead opt for using next-routes’s pushRoute method.

Basic example:

import { connect } from 'react-redux'
import { Router } from '../routes'

// ----

export default class Link extends React.Component {

  handleClick(evt, url) {
    evt.preventDefault()    
    Router.pushRoute(url)
  }

  render() {
    const { url, title } = this.props

    return (
      <a href={ url} onClick={ (evt) => this.handleClick(evt, url) }>{title}</a>
    )
  }
  
}

This seems to figure it out and I don’t see the Error Flashing. But it feels a bit quickfixy.

Your href and as props shouldn’t be the same, href is the real url, if you have pages/blog.js and receive id as a query then href should be /blog?id=${x.id} and as is your pretty custom url in this case /blog/${x.id}.