How should I use cookies with Svelte and Sapper?
Asked Answered
N

1

7

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?

Navicert answered 17/12, 2019 at 11:31 Comment(7)
way to guarantee code only runs client-side JS files send from server are runned at client side, cookies are send to server with request - this is all you need.Elephantiasis
In Svelte / Sapper, the code also runs (and fails) server-side.Navicert
What I'm saying if controller sends files to client, they are not interpreted any more at server-side.Elephantiasis
In Svelte + Sapper, that's not accurate. Javascript code will be executed on the client, server, or (usually) both.Navicert
You're suggesting after sending js to client JS comes back to server and it's executed again - I don't think so. Server-side rendering is one thing - JS functionality on client side is another thing.Elephantiasis
Have you used Svelte and Sapper before?Navicert
Let us continue this discussion in chat.Navicert
N
4

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");
}
Navicert answered 17/12, 2019 at 13:0 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.