Search code examples
vercelsveltekit

Environment Variables in SvelteKit Throwing Error on Deployment to Vercel


I am working with SvelteKit and deploying to Vercel. I am using environment variables and having a tough time getting this to work. The error below shows on my Vercel Dashboard when I push to Git.

RollupError: "PRIVATE_API_KEY" is not exported by "$env/static/private", imported by "src/routes/account/+layout.server.js".

I found the following in the docs. It shows creating a +layout.server.js file and then states you can pull that into the +layout.svelte or +page.svelte components through data.

layout.server.js

import { PRIVATE_API_KEY } from '$env/static/private';
 
/** @type {import('./$types').LayoutServerLoad} */
export function load() {
  return {
    deploymentGitBranch: PRIVATE_API_KEY,
  };
}

+layout.svelte

<script>
  /** @type {import('./$types').LayoutData} */
  export let data;
</script>
 
<p>This staging environment was deployed from {data.deploymentGitBranch}.</p>

My .env file is as shown below.

# Public
PUBLIC_API_KEY=public


# Private
PRIVATE_API_KEY=123456789

I did search through this site and found the following but this seems dated and I could not get it to work. Even after following these steps the issue persists?

How do I resolve this error? Any help would be greatly appreciated.


Solution

  • This looks like a variable not known at build time, so it should also not be imported from the static environment variables.

    Use $env/dynamic/private instead.

    This module provides access to runtime environment variables, as defined by the platform you're running on.

    The .env file will not be loaded, so the variables have to be configured in Vercel.