kit: Env variables are not accessed by vite in PROD

Describe the bug

I am using the docker image for the production build. I have set my environment variables in docker and they are accessible by using env. But when I build the app these are not accessed by Vite.

Please help me here!

Reproduction

Create Svelte kit app by started.

  • create the docker image
  • Create the env variables in the docker system.
  • use the VITE_ as a prefix.

Logs

No response

System Info

Undefined

Severity

blocking all usage of SvelteKit

Additional Information

No response

About this issue

  • Original URL
  • State: closed
  • Created 3 years ago
  • Reactions: 5
  • Comments: 17 (6 by maintainers)

Most upvoted comments

I solved this by building the .env from a shell script, using a pre-populated .env with =null for each variable.

docker-entry.sh:

#!/bin/sh

SRC=.env
OUTPUT="// generated"

while IFS="" read -r line || [ -n "$line" ]; do
    use_line=$line

    if expr "$line" : "VITE" > /dev/null; then
        ENVIRONMENT_VARIABLE_NAME=$(echo "$line" | sed -re 's/=.*//g')
        value=$(printenv "$ENVIRONMENT_VARIABLE_NAME")

        if [ "${value}" ] && [ "${value-x}" ]; then
            use_line="$ENVIRONMENT_VARIABLE_NAME = '$value';"
        fi
    fi

    OUTPUT="$OUTPUT\n$use_line"
done <$SRC

echo "$OUTPUT" > $SRC

http-server dist

https://stackoverflow.com/a/77490465/17756110 If anyone is still looking for the solution to this problem.

This is an incredibly ugly hack to get this working, it converts process.env variables prefixed with VITE_ to an .env file before before runtime.

docker build file

...

COPY . .

CMD ["pnpm", "run", "preview"]

package.json (I have to use preview instead of dev, as otherwise webworkers break on ff, ive been having fun 😕)

"scripts": {
    "build": "node ./.patch/env_bind.js && vite build && rm .env",
    "preview": "node ./.patch/env_bind.js && vite build && rm .env && vite preview --host"
},

.patch/env_bind.js

// Vite imports environment variables through import.meta.env. import.meta.env does not import docker variables like process.env does. This file patches this.
import fs from "fs";

const vite_env_variables = Object.entries(process.env).filter(variable => variable[0].startsWith("VITE_"));
const vite_env_variable_string = vite_env_variables.map(variable => variable[0] + "=" + variable[1]).join("\n");
fs.writeFileSync(".env", vite_env_variable_string, {encoding: "utf-8"});

I don’t recommend using this, but in my case I dont have another choice until import.meta.env gets all the env variables