sveltesapper

Why would a preload behave differently in the local dev version of the site vs. the local exported version of the site?


Svelte 3.34.0, Sapper 0.28.10.

File at /src/routes/data/index.svelte. Url pattern is http://localhost:3000/data/?day=40 or http://localhost:3000/data/ (defaults to current day). The page fetches JSON data from a remote url and displays it.

<script context="module">
  import { buildDataUrl, formatDate } from '../../helpers';
  import moment from 'moment';

  export async function preload(page) {
    const query = page.query;
    let day = Number.parseInt(query.day);
    if (Number.isNaN(day)) day = moment().dayOfYear();
    console.log(`preload fired, day: ${day}, ${JSON.stringify(query)}`);
    const get = await this.fetch(buildDataUrl(day), {

When I run this locally in dev mode with sapper dev the url query param is respected and used correctly. The page will re-render when the query string changes, either by editing it or clicking on a link on the page.

When I run this locally with npx sapper export && npx serve __sapper__/export (see docs here) and go to http://localhost:5000/data/?day=40 the day value always defaults to the current day, regardless of what is in the query string. Even using ?day=a will not change the behavior -- this should result in an error.

Docs for preload are here.

This feels like a bug but I can't be certain.


Solution

  • From the chat with the devs on Discord I found that you have to use the page store to access the query string and then run any async fetches in your page script, not module script.