Nuxt - dynamic params after building does not work

Viewed 2543

In a Nuxt ("spa" mode) project I have a url with a dynamic param /shop/:product, which can be as such:

    /shop/ipad-128gb-rose-gold
    /shop/subway-gift-card
    /shop/any-string

etc.

Using this directory structure works fine in development environment:

pages/
  shop/
    _product.vue

However it does not work in production. Looking to the generated bin/ folder I see that there is nothing inside shop/ directory. And I see that Nuxt mentions a solution here: https://nuxtjs.org/api/configuration-generate/#routes

But in my situation, I don't know what the :product param will be (could be any string).

I am fetching the product details in pages/shop/_product.vue from the server (if it exists), otherwise handling the error. So now how do I do that in a production build?

I think I am misunderstanding the Nuxt solution -- am I really supposed to generate all possible routes for every existing product slug??

2 Answers

The solution for me was to use:

// nuxt.config.js

export default {
  ...
  generate: {
    fallback: true
  }
}

I am serving the app out of the built dist/ folder. And I came across this in the Netlify deployment docs:

For a single page app there is a problem with refresh as by default on netlify the site redirects to "404 not found". For any pages that are not generated they will fallback to SPA mode and then if you refresh or share that link you will get Netlify's 404 page. This is because the pages that are not generated don't actually exist as they are actually a single page application so if you refesh this page you will get a 404 because the url for that page doesn't actually exist. By redirecting to the 404.html Nuxt will reload your page correctly in SPA fallback.

The easiest way to fix this is by adding a generate property in your nuxt.config and setting fallback: true. Then it will fallback to the generated 404.html when in SPA mode instead of Netlify's 404 page.

References:

When you generate static pages, it produces directories and index.html in each one. How did you expect to have it dynamic if you serve static HTML?

You have 2 solutions:

  1. don't use npm run generate. Run nuxt on the server. Using this solution, you avoid ajax in browser. Instead, nuxt performs it and sends the HTML to the browser. Good for SEO.

  2. have your web server (nginx) point all requests to /index.html - at that point, javascript takes over and it can correctly find the slug and query the products via ajax. Bad for SEO because you need to use ajax to get the content after page finishes loading.

Documentation and configuration about this can be found at nuxt's web.

Related