nuxt / nuxt

The Intuitive Vue Framework.
https://nuxt.com
MIT License
54.97k stars 5.03k forks source link

Middleware causes race condition in hydration/rendering using navigateTo #14256

Closed Pautomagi closed 2 years ago

Pautomagi commented 2 years ago

Environment


Reproduction

https://stackblitz.com/edit/github-v6arv4

Describe the bug

We found a bug that seems to happen when using middleware to check for valid data before doing a redirection. Note that this might be caused by wrong usage of state and/or middlewares.

tldr: navigateTo in middlewares causes DOM to fail hydration and keeps nodes from previous and navigated to view.

Steps to reproduce

I am using https://dummyjson.com/ for data. ID is a number from their https://dummyjson.com/products endpoint

ID 1 and 2 are apple products. Go higher than 10 for others.

  1. Navigate to /:id/2
  2. If product brand is 'Apple' you should be redirected to /:id/product
  3. The product.vue should render and show the title "Hello from product" with a red background

Actual result

Redirected but something happens to the DOM on hydration. You can see that the background on /:id/product is not red when redirection happens but the content is correct. If you refresh the /:id/product page or access directly you will see it render correctly.

Additional context

No response

Logs

No response

danielroe commented 2 years ago

The issue here is that the middleware has already run before you fetch the data. So it doesn't redirect on SSR. But on client-side, the data is already set from the server, so it does run.

You should ensure that the data is present before your middleware runs if you need to depend on it for that decision.