Use JSON to pass data from SSR to improve performance

CyberAP
0
CyberAP
commented 4 months ago

What problem does this feature solve?

Using JavaScript to pass data from SSR to an app through global context is not efficient.
JSON, on the other hand, offers a much better performance and could be used instead. Explanation in v8 blog, Benchmarks (performance increase up to 2 times)
This is especially important for apps with a lot of state.

What does the proposed changes look like?

This code:

<script>window.__NUXT__ = { data: {} /* some state */ }</script>

Turns into this:

<script id="NUXT_STATE" type="application/json">
{ data: {} }
</script>
// somewhere in app init
const stateEl = document.getElementById('NUXT_STATE');
const state = JSON.parse(stateEl.textContent);
app.state = state;
idea
0
Timkor
6
Timkor
commented 4 months ago

What about circulair references? Or types which are not supported by JSON?

0
CyberAP
0
CyberAP
commented 4 months ago

For circular references we have: https://github.com/WebReflection/circular-json
This could be enabled in a nuxt config for those who really need that.

For unsupported JSON types could you elaborate a little bit more? What's the usecase?

0
manniL
6.7k
manniL
commented 4 months ago

Thanks for the information! We read that article as well but things are a bit more complicated here. For Nuxt 2, we decided to go with devalue (our fork) instead of pure JSON.stringify for a couple for reasons. This won't change in Nuxt 2 to avoid breaking changes.

0
CyberAP
0
CyberAP
commented 4 months ago

@manniL could you unveil these reasons if possible? I'm really curious when JSON is not appropriate as a DTO.

0
aldarund
983
aldarund
commented 2 months ago

circular-json seems to be replaced by flatted. I tested flatted and devalue on 120kb payload. Without circular.
devalue -> 1600 ops
flatted -> 630 ops
json.strigify -> 4900 ops
Reasons for devalue instead of json listed on the devalue page itself.

repeated references ([value, value])
undefined, Infinity, NaN, -0
regular expressions
dates
Map and Set

For example undefined values just got stripped by json.stringify

0
Informations
Feature Request โ€ข Open
#c9586 - Created 4 months ago