Skip to content

(Redux) Script tag with window.__INITIAL_STATE__ = { ... } in html response from server #467

@vogelino

Description

@vogelino

First of all, thank you for creating such a nice framework, it works like a charm.

I am writing a website with next.js and Redux. I use getInitialProps to preload data from the contentful API. If I get this right, this function is first called once on the server, then my App is beeing rendered with the preloaded data and the response is retrieved with the full rendered html. Finally on the client side, getInitialProps is executed again. There, it fetches my preloaded data again and initializes the store to be handled there.

I was just wondering if there was a way to avoid the first client-side request when executing getInitialProps by allowing to expose the initial Redux state in a script tag when retrieving the rendered html from the server. Like this:

<script type="text/javascript">window.__INITIAL_STATE__ = { ...myStateHere... }</ script>

Doing this would allow me to use this global variable as an initial state in the store creation on the client side after the first load. After that, when navigating with the <Link /> component, the getInitialProps would be executed again and I would check if window.store is already existing. If so, I would skip the data fetching.

Does it make sense to you? Is there a way to access the rendered html output before it is sent to the browser and to extend it?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions