Jonathan Chang
Jonathan Chang

Reputation: 305

How would you make an API call and pass data to client with Sveltekit?

I've just begun learning Sveltekit. I'm following the tutorial for Auth.js for making a custom login page (https://authjs.dev/guides/pages/signin), which passes a mapping of the providers to some properties to use client-side. I have done this exact thing in Next.js, but I'm running into an issue with Svelte giving me the error: "Internal server error: Cannot import $env/dynamic/private into client-side code". However, I'm not importing any private variables into the client-side.

Internal server error

Here's my system environment:

  System:
    OS: Windows 11 10.0.22631
    CPU: (20) x64 13th Gen Intel(R) Core(TM) i5-13600K
    Memory: 24.62 GB / 63.76 GB
  Binaries:
    Node: 20.11.1 - C:\Program Files\nodejs\node.EXE
    npm: 10.8.1 - ~\AppData\Roaming\npm\npm.CMD
  Browsers:
    Edge: Chromium (125.0.2535.92)
    Internet Explorer: 11.0.22621.3527
  npmPackages:
    @auth/sveltekit: ^1.2.0 => 1.2.0
    svelte: ^4.2.18 => 4.2.18

Specifically, I could have a "test.ts" with

import { AUTH_SECRET } from "$env/static/private";

export const testValue = 1;

And then under "/src/routes/+page.svelte", I have

<script lang="ts">
import { testValue } from "./test";
console.log(testValue);
</script>

"testValue" is defined in a file that imports a private variable, but it does not contain the environment variable. But Svelte still throws the error. I've tried passing the value to +page.server.ts, putting it in a load function, nothing is working for me. If I delete the import from the page, then the error goes away.

So how do I get data from presumably any API that requires a private key and pass it client-side?

Upvotes: 0

Views: 506

Answers (1)

Jonathan Chang
Jonathan Chang

Reputation: 305

Okay, never mind. I don't know if this is the canonical pattern since it seems very unintuitive, but apparently this would work if I

+page.server.ts

import { testValue } from "./test";
export function load() {
    return {
        testValue
    };
}

+page.svelte

<script lang="ts">
    $: console.log(data.testValue};
</script>

All the prior examples in the documentation and everywhere have noted that if the private environment variable is directly imported client-side, it throws an error. It turns out the error is thrown even if the the private environment variable is used anywhere in a file that contains something that is imported. That makes me wonder if, in this case, "test.ts" is accessible to the client in its entirety despite only "testValue" being exported, or is it just Sveltekit's detection mechanism is imprecise or overly cautious?

Upvotes: 0

Related Questions