Search code examples
javascriptsappersvelte-3

How should I use cookies with Svelte and Sapper?


I'm using Svelte and Sapper for a project. Let's say I have some code that needs to read a cookie before it runs, and that code is in a route at say /profile or something.

My understanding is that Sapper provides no guarantees where the code will run. If I put the code in regular <script> tags or maybe an onMount block, when a user requests /profile directly from the server, the code still execute on the server (and fail) but then execute again on the client:

<script>
import { getCookie } from "../../myUtilities.js";

const myCookieValue = getCookie("myCookie");

async function myRuntimeAction() {
   let res = fetch(`https://www.example.com/api/${myCookieValue}`);
   ...
}
</script>

<form on:submit|preventDefault={myRuntimeAction}>
    <button>
      Take Action!
    </button>
</form>

Is there an idiomatic Svelte / Sapper way to guarantee code only runs client-side, when it has access to cookies?


Solution

  • I found two ways to solve this:

    1. Access cookies inside of functions that will only be executed client-side at runtime

    The root of the problem is that my variable declaration was a top-level declaration. Simply moving the code that accesses the cookie inside of a function that is called only at runtime fixes the issue:

    async function myRuntimeAction() {
       const myCookieValue = getCookie("myCookie");
       let res = fetch(`https://www.example.com/api/${myCookieValue}`);
       ...
    }
    

    2. Check process.browser before trying to access cookies

    Svelte exposes process.browser to ensure code only executes in the browser:

    if (process.browser) {
        const myCookieValue = getCookie("myCookie");
    }