Next.js: routeChangeComplete event called on page load for routes with params

Created on 3 Apr 2020  路  8Comments  路  Source: vercel/next.js

Describe the bug

When ASO is enabled and you navigate to pages with params the routeChangeComplete is called. On page load:

This is a problem because routeChangeComplete isn't called when loading pages that don't have parameters. This inconsistency makes things difficult.

In my case I'm trying to call analytics events on route change and page load. The page view event is called on page load (using an effect) but then the routeChangeComplete is immediately called which fires the page view again.

To Reproduce

Reproduction example here

Steps to reproduce:

  1. Start the server
  2. Go to / and see that route change is NOT logged
  3. Add any query param, e.g. /?id=1. Reload the page and notice route change is called
  4. Go to /posts/1 and see that route change is logged on page load
  5. Add getInitialProps to _app and this doesn't happen any more

Expected behavior

I would expect either:

  1. Route change is always called on page load while ASO is enabled.
  2. Route change is not called on page load for pages with params

(I'd also not expect the query object to be empty, but that's probably a separate issue)

Screenshots

N/A

System information

  • OS: macOS
  • Browser (if applies) Chrome
  • Version of Next.js: 9.3.4

Additional context

N/A

needs investigation

Most helpful comment

@valse that's great, but it is a workaround. It would be great to understand reasons behind the code and to fix root problem.

All 8 comments

@timneutkens I can probably take a look into it myself if I can get pointed in the right direction.

Same problem here.
routeChangeComplete event is called because this evaluates to true https://github.com/vercel/next.js/blob/a0c683208abdce84934061f6efd2b90de52d99b9/packages/next/client/index.js#L103
Additional condition was probably firstly introduced here https://github.com/vercel/next.js/commit/45832e44219b281eab5569374f3b2cb2f651e755
I don't know what hydrateProps.__N_SSG means, probably Not Static Site Generation?

I've tried local development and static export and in both cases data.nextExport was false and __N_SSG was true.

Maybe someone from core team can explain what was intended here.

Hi, check it out this discussion #12306 about avoid double analytics views on page load

However this is a big problem when you must trigger something on change routing only: I have this need and at the moment I can't find a workaround to skip the first "bad" routeChangeComplete trigger :(

@valse that's great, but it is a workaround. It would be great to understand reasons behind the code and to fix root problem.

Was this page helpful?
0 / 5 - 0 ratings