Jump to main content

Server-Side Props

Passing dynamic data from your views to your SPA.


Overview

DxSvelte allows you to attach a data dictionary to your render function within views. When you do so, that dictionary is serialised into JSON by the renderer and exposed to the corresponding Svelte view component.

As there is no default schema enforcement in place between the back-end and front-end, you will need to be careful to test your objects in the Svelte app when using them in components to avoid undefined value errors caused by any mismatches. You may want to consider using a JSON schema validator.


Server-Side Rendering

Upon first page load, DxSvelte attaches the initial SSP payload to the document. When the SPA starts up and rehydrates the DOM, it defers to the initial payload it already has instead of needlessly re-fetching it from the server.

This is all default behaviour and requires no additional configuration.


Passing Data From Views

When defining your view, pass a dictionary in as the second argument:

from dxsvelte import render

def index(req):
    data = {"someKey": "World"}
    return render(req, data)

Consuming Server-Side Props

In your corresponding Svelte view component, you can import and consume the data by importing an automatically-generated store from @page:

<script>
  import { ServerSideProps } from "@page";
  $: data = $ServerSideProps;
</script>
{#if data}
    Hello {data.someKey}!
{/if}

@page is specifically and only available to Svelte view components, as opposed to @common, which is available globally.


Store Behaviour

It's worth noting that these stores are generated per view and not per path, as a view with a Django URL dispatcher can represent an essentially infinite number of 'pages'.

The store data is replaced with a new object when the user navigates between paths sharing a single view. Be mindful of this behaviour if you're attempting to use the stores differently to how they are being used in the scenarios above.