Search code examples
sveltevercelsveltekit

Environment variable in markup codes of SvelteKit could not work at Vercel


Hi~ I am a developer in South Korea. I am not good at english yet. But I have a question about SvelteKit. I wrote the below codes in +page.svelte as SvelteKit tutorial. This code worked well in local dev mode.

<script>
  import { env } from '$env/dynamic/public';
</script>

<main style:background={env.PUBLIC_THEME_BACKGROUND} style:color={env.PUBLIC_THEME_FOREGROUND}>
  {env.PUBLIC_THEME_FOREGROUND} on {env.PUBLIC_THEME_BACKGROUND}
</main>
.....

Then I deployed the above codes to Vercel, build and published. But I got some error that is undefined in import { env } from '$env/dynamic/public' Other codes of the SvelteKit tutorial which was deployed to Vercel worked well except this code. That is, This error is not problem of the adapter or runtime of Vercel. Ok, I already changed them but could not fix this error.

So, I created +page.server.ts file and I moved the above codes into that like below.

import { env } from '$env/dynamic/public';

export function load() {
  return { env: { 
    PUBLIC_THEME_BACKGROUND: env.PUBLIC_THEME_BACKGROUND,
    PUBLIC_THEME_FOREGROUND: env.PUBLIC_THEME_FOREGROUND,
  }};
}

And I changed the markup file(+page.svelte) like below.

<script>
  export let data;
</script>

<main style:background={data.env.PUBLIC_THEME_BACKGROUND} style:color={data.env.PUBLIC_THEME_FOREGROUND}>
  {data.env.PUBLIC_THEME_FOREGROUND} on {data.env.PUBLIC_THEME_BACKGROUND}
</main>
.....

Now, This code work well. In short, Why cannot $env/dynamic/public work in markup file at Vercel?

  • Changed the adapter of Vercel in svelte.config.js from edge to nodejsXXX.
  • Changed the build script in package.json from vite build to mv ./env.local to ./.env && vite build and remove .env from .gitignore.
  • Set up Vercel's environment variables in Project Settings.

Solution

  • Instead of reading your environment variables from your directory, have you considered using Vercel's environment variables? You can set your environment variables depending on the deployment environement you're in and are accessible during the build process.

    enter image description here

    You can call them in your code like this. enter image description here

    Also, if you want a copy of your environment variables locally you can just run:

    vercel env pull 
    

    For the reason as to why your env variables aren't available in your mark up file. Vercel utilizes edge functions to handle requests, and these edge functions have limited access to environment variables at build time.

    $env/dynamic/public in SvelteKit relies on the build process to access and inject environment variable values into your code. Since Edge Functions on Vercel don't have this capability readily available, the environment variables aren't accessible directly in your markup file during the build.