Nuxt.js: Full static mode dynamic pages payload 404 errors (i18n module)

Created on 14 Jul 2020  路  39Comments  路  Source: nuxt/nuxt.js

Versions

  • nuxt: v2.13.3
  • node: any

Reproduction


Additional Details


When using nuxt-i18n with full static generated mode there are still 404 errors for payload.js on dynamic pages.

Related https://github.com/nuxt/nuxt.js/issues/7559 https://github.com/nuxt/nuxt.js/issues/7648 https://github.com/nuxt/nuxt.js/issues/7622

Steps to reproduce

Check codesandbox.

About page tries to pre-fetch "_nuxt/static/1594718554/fr/test/payload.js" and gets 404 error in console log.

What is Expected?

Payload shouldn't be fetched because it wasn't generated at all.

What is actually happening?

Still 404 errors.

bug-report

Most helpful comment

Hi there,

We are aware of this issue but this one is a bit tricky since we actually need to generate a manifest to know what routes has been statically generated (vs ignored), this manifest can have a huge size based on the number of generated route and also affect performances.

This does not mean we cannot solve it but we have to take the right decision about it.

All 39 comments

@Atinux here is a information that you've requested:

Github: https://github.com/divine/nuxt-payload-error
Surge: http://ceaseless-grain.surge.sh/about

Error: Uncaught SyntaxError: Unexpected token '<' payload.js:1

Normally it's a 404 error but on surge it's unexpected token, quite interesting.

Thanks!

I'm having the same Uncaught SyntaxError: Unexpected token '<'. (404)

I noticed that in the generated HTML files, the src of the payload.js and state.js files does not have the router base param concatenated with it (when running inside a domain directory, for example).

Yeah, I just passed all the dist html files into a shell function that concatenated the router.base and everything seems to work.

I have seen several of these 404 cases in the static folder, and in my case, the error was:

As the build process now happens in 2 steps (build and export), I was injecting the environment variables only in the first process. When the export ran, without the injected variable, it exported the last static things without the variable (in my case, the router.base).

In short: my implementation error. If you come by, check if all your environment variables are being injected in the 2 moments. (not all are necessary for export)

Hi @lucasvst. It seems you have another issue that causes payload not found an error with router.base option (not dynamic routes nor i18n). In that case would be much appreciated if you can make a new issue with github reproduction.

@pi0 In fact, was not an issue. Was an implementation error (my implementation). I was not injecting my variables on export step.

I let the comment here for future users check this point before.

@Atinux @pi0 guys it's still broken, could you please reopen this issue?

Github: https://github.com/divine/nuxt-payload-error
Codesandbox: https://codesandbox.io/s/throbbing-feather-v7nnx
Surge: http://jobless-head.surge.sh/

Error: Uncaught SyntaxError: Unexpected token '<' payload.js:1

Quite interesting fact this time on surge reactivity is broken because it can't find commons.297bbcd.js:1
However, on localhost fr/test/payload.js net::ERR_ABORTED 404 (Not Found), also the same error on codesanbox as well.

Thanks!

@Atinux @pi0 any update?

I've updated with latest version on Github, CS and Surge link is http://careful-money.surge.sh/about/

So there is currently no way to use i18n in a full static app ?
Should have read this before translating the entire app..

I actually have the same issue without using i18n.
I use the full static mode but have several fully dynamic pages which are not statically pre-rendered. For these pages, the payload.js get requested but there's obviously a kinda 404 error (Uncaught SyntaxError: Unexpected token '<').

  1. Open https://stiki.fyi/daheq/notes/culture
  2. Check console

I have the same issue than @felixheck, full static website with a link to a dynamic page (37M possible routes so no pre-rendering possible).

My NuxtLink's redirecting to this dynamic pages have the no-prefetch attribute but a /payload.js request is still triggered on click, resulting in 404 and then successfully loading the dynamic page, but it takes extra time (waiting for the 404 to happen).

having the same issue as @felixheck @nicolasbeauvais, and no-prefetch also doesn't work for me.

Related #8003

Hi there,

We are aware of this issue but this one is a bit tricky since we actually need to generate a manifest to know what routes has been statically generated (vs ignored), this manifest can have a huge size based on the number of generated route and also affect performances.

This does not mean we cannot solve it but we have to take the right decision about it.

Does anyone have an interim work around? Have attached what I'm getting...
Screenshot 2020-09-15 at 19 26 57

Does anyone have an interim work around? Have attached what I'm getting...
Screenshot 2020-09-15 at 19 26 57

There is no known work around for this problem.

Thanks!

i am sorry.i can't speak english

I have a similar problem.
npm run build generated file
npm run start run file
It show route/payload.js net::ERR_ABORTED 404 (Not Found) in console.
I just load the route and it appears

Is there a problem with my WebPack configuration?(default configuration )

Versions

  • nuxt: v2.14.1
  • node: any

thank you very much for seeing this question.

Thanks!

Hi folks! I am getting exactly the same result.

image

  • Nuxt: 2.14.6
  • Target: static
  • Deploy: Vercel (@nuxtjs/now-builder)

Hi.
I'm having the same issue.

How can I prevent those errors to be displayed? We didn't have that error before but we added GTM to the project so we had to update Nuxt version and after that update we came across this issue.

If someone has a work around for this issue please post it here!

The issue happens as soon as I build a link for a dynamic page. I'll try the no-prefetch feature for the links but it will happen again once I get into the dynamic page.

  • Nuxt 2.14.6
  • Target: static

@Atinux any update on this? I can understand this might be not a priority but until nuxt 3 release this is really bugging everyone.

Thanks!

I will look at this ASAP

I found a stable workaround for those of you that use Vercel by leveraging the edge-network caching (Serverless Pre-Rendering), I think it's a good compromise between SSR and static generation that should work for most use cases.

Nuxt.js config

You need to deploy your app with a server target, and exclude all pages that you do not want to be statically generated by Nuxt.js (routes that can render thousands of different pages should in most case be excluded):

// nuxt.config.js
export default {
  target: 'server',

  generate: {
    exclude: [
      /^\/dynamic-route\//,
    ]
  },
}

Vercel config

Now as we are deploying in server mode, we need to use @nuxtjs/vercel-builder to run our code on Vercel. By using the generateStaticRoutes option, all non excluded pages will be statically rendered at build time. For the dynamic pages that we excluded, adding the Cache-Control: s-maxage=43200, stale-while-revalidate will tell Vercel to cache all server-side-rendered pages for 12h, if the cache is expired, Vercel will send the last saved version of the page to the client while simultaneously updating the cache in the background. More info on Vercel caching strategy here.

{
  "version": 2,
  "builds": [
    {
      "src": "nuxt.config.js",
      "use": "@nuxtjs/vercel-builder",
      "config": {
        "generateStaticRoutes": true
      }
    }
  ],
  "headers": [
    {
      "source": "/(.*)",
      "headers" : [
        {
          "key" : "Cache-Control",
          "value" : "s-maxage=43200, stale-while-revalidate"
        }
      ]
    }
  ]
}

This solution has a tiny performance cost for the first render of SSR dynamic pages, but the increased flexibility between static and dynamic is totally worth it for me.

Awesome! Thanks for sharing @nicolasbeauvais

Hi all, I'm having a similar problem around payloads, if there's a more relevant issue let me know, but:

1) when I generate dynamic routes with target: "static" in my nuxt.config.js the routes don't seem to accept their payload, and
2) when I don't use target: "static" the head() methods I include on those dynamic routes aren't included in the index.html for those routes (as found in dist after generate)

I've documented better in SO questions here:
1 - https://stackoverflow.com/questions/64148659/nuxtjs-dynamic-routes-not-accepting-payload-when-full-static
2 - https://stackoverflow.com/questions/64147401/in-nuxtjs-will-dynamic-route-head-tags-populate-for-seo

If anyone could give me pointers to address either problem, that'd be amazing, let me know if I need to open a new issue, thanks!

@Sford4 sorry but I don't think that SO is a better place to document it.

You'd better writing it here because actual developers of nuxt are here. 馃槈

@divine sounds good, here's the write up:

When I run nuxt generate, I create routes like so:

***nuxt.config.js***

generate: {
    routes() {
      return axios
        .get(`${process.env.ROOT_URL}/businesses`)
        .then(res => {
          return res.data.map(business => {
            return {
              route: `/business/${business.id}`,
              payload: business
            };
          });
        });
     }
}

This successfully creates my dynamic routes, which accept a payload from generation. Each route should have their own headers, from my business component:

***business.vue***

async asyncData({ params, store, error, payload }) {
    if (payload) {
      console.log('GOT PAYLOAD!', payload)
      return { business: payload };
    } else {
      // other stuff
    }
})
...
...
...
head() {
    return {
      title: this.business.name,
      meta: [
        {
          hid: `businessPageDescription-${this.business.id}`,
          name: "description",
          content: this.business.description,
        },
        {
          hid: `businessPageKeywords-${this.business.id}`,
          name: "keywords",
          content: this.business.keywords,
        },
      ],
    };
  },

During nuxt generate with target: "static" on in my nuxt.config.js, the console.log above is hit for each dynamic route, so I know it's receiving its correct payload in asyncData.

After nuxt generate my dist folder has a subfolder for each dynamic route, but the index.html for each has only a few lines inside , and when I visit the page for each on the browser no content specific to the dynamic route appears (the navbar from my layout component comes up fine).

Navigation in-app works fine, so if I go to a different page and come page to my dynamic route content will appear, so asyncData works, accepting the payload is the trouble.

Without target: "static" things work as expected, the index.html for each in dist has plenty in it, and the page loads the desired content when visited, although the head() method in business.vue is not generated (it will populate on the client when the component mounts).

Question 1: Any ideas how to get my full static business pages to accept and hold onto their payload?

Question 2: My whole goal is to prep my dynamic routes for SEO, so the head() method NOT working during generate in either scenario concerns me (right now the tags are filled with defaults from my nuxt.config.js), will crawlers still get my dynamic content for SEO purposes either when I use target: "static" or not?

Again, let me know if I need to raise a new issue, or if there's another forum where I can get help. Thank you so much!

We're experiencing the same, our payloads which are triggered by nuxt-links just contain the rendered / page. Looking forward to a solution!

Same error using target:static and no other property touched. I don't have the i18n module this happens also with no external modules or anything else:

<nuxt-link :to="`/boards/${board.id}`" >View</nuxt-link>

Since board.idis dynamic and it doesn't get generated in the routes the payload returns a 404 causing the Uncaught SyntaxError: expected expression, got '<' error.

I think that there should be a way to catch these errors for dynamic routes

This issue seems to have been raised multiple times since June and then closed (#7559 #7622 #7648), once tagged "available soon".

Is there a solution or a workaround?

Error: Uncaught SyntaxError: Unexpected token '<' payload.js:1
Normally it's a 404 error but on surge it's unexpected token, quite interesting.

@divine Surge rewrites all URLs that don't have a corresponding static file to /200.html. So, the error is different because a request for "payload.js" is returned, but it is not a javascript file that was expected.

Error: Uncaught SyntaxError: Unexpected token '<' payload.js:1
Normally it's a 404 error but on surge it's unexpected token, quite interesting.

@divine Surge rewrites all URLs that don't have a corresponding static file to /200.html. So, the error is different because a request for "payload.js" is returned, but it is not a javascript file that was expected.

I know, but it's pretty lame to redirect .js files at least. Showing error is important instead of giving plain 200.html content.

Anyways let's keep discussion going on actual issue:

This issue seems to have been raised multiple times since June and then closed (#7559 #7622 #7648), once tagged "available soon".

Is there a solution or a workaround?

Workaround is to use server mode instead of static one. As I remember you were using Firebase so basically there is no resolution.

@Atinux any updates?

Thanks!

Not a solution, but a simple patch to the issue for me was to create a noop payload.js file, and then rewrite all requests to non-existent payload.js to it:

{
  "source": "/admin/**/payload.js",
  "destination": "/payload.js"
}

Back to the solution:

My understanding that payload.js is related to "Smart Prefetching". Is this correct? If so, is there any way to opt out of it?

On my home page, Nuxt prefetches a bunch of payload.js files, all of them containing nothing but
__NUXT_JSONP__(<path>, {data:[{}],fetch:[],mutations:[]});

Is there a way to disable the prefetch for certain routes? Or maybe make the prefetch smarter by not prefetching the payload if it is known at build time to be empty?

Same issue, deploying to netlify (unexpected token -> js files containing html index page, I guess server defaults to index instead of not found 404 on netlify). Using PWA it immediately happens on opening of the app when the loading screen is shown.

I narrowed it down to:
My corrupted PWA installs are fixed after clearing the application (clear site data) via chrome inspect devices.

After the new netlify deployment the PWA has the issue again (seems to point to old resources), when I use chrome inspect to clear application cache it works again (until next deployment).

Root cause (404 or unexpected '<')
The cause is that it links to the now-outdated files... The outdated files are no longer there and therefore you get a 404 error. However depending on your server configuration (e.g. on surge/netlify/other servers), it defaults to the index file instead of getting a 404 error). This causes your old js files to now contain the index content, which in turn gives you an unexpected token '<' error. This happens after the user opened the site and subsequent visit again when a newer version has been deployed.

Current workaround
Clear your site data via chrome inspect devices.

@divine can you reproduce it following my steps?

But what's the real cause for pointing to the old js files? Is it a workbox cache issue?

Current workaround
Clear your site data via chrome inspect devices.

@divine can you reproduce it following my steps?

But what's the real cause for pointing to the old js files? Is it a workbox cache issue?

@Anima-t3d I think you're missing the point that the error happens on dynamic link routes which were'nt generated initially.

Basically your workaround doesn't solve it.


I will look at this ASAP

Any update on this @Atinux ?

Working on a workaround :)

Not sure it's directly related, but when I enable no sniffing of the content type I get a slight variation of the error:

Refused to execute script from '...payload.js' because its MIME type ('text/html') is not executable, and strict MIME type checking is enabled.

@Anima-t3d I think you're missing the point that the error happens on dynamic link routes which were'nt generated initially.

Seems like the issue I have is caused by: https://github.com/nuxt-community/pwa-module/issues/381

So although the symptoms are the same the cause seems to be different, just thought to add here for others who end up here.

I've had the same problems with 404 errors for payloads on dynamic pages. These all disappeared when using [email protected]. Thank you!

Was this page helpful?
1 / 5 - 1 ratings

Related issues

shyamchandranmec picture shyamchandranmec  路  3Comments

gary149 picture gary149  路  3Comments

danieloprado picture danieloprado  路  3Comments

bimohxh picture bimohxh  路  3Comments

vadimsg picture vadimsg  路  3Comments