T
TanStack6mo ago
flat-fuchsia

Accessing environment variables (env vars) in built Tanstack Start app

After building my app in a Docker image with vinxi build, the app is not detecting my environment variables after I start it up. From what I understand, you can declare environment variables, even VITE_ prefixed ones, and they will be detected once the server starts running and consumed by the backend and frontend. Any ideas why this might be happening to me?
2 Replies
flat-fuchsia
flat-fuchsiaOP6mo ago
I was getting confused because my .env was available in my local environment when running bun run build but is not in the Docker build due to my .dockerignore. To get around this, I have moved build/run into my entrypoint. My Dockerfile:
FROM imbios/bun-node:1.2.8-20-slim

# Set up monorepo context
WORKDIR /repo
COPY . .

# Install pnpm in the builder stage
RUN bun install --frozen-lockfile

# Set up Docker entrypoint script
WORKDIR /repo/apps/frontend

# Set production environment
ENV NODE_ENV=production

# Expose the port the app will run on
EXPOSE 3000

# Set the entrypoint
ENTRYPOINT ["./docker-entrypoint.sh"]
FROM imbios/bun-node:1.2.8-20-slim

# Set up monorepo context
WORKDIR /repo
COPY . .

# Install pnpm in the builder stage
RUN bun install --frozen-lockfile

# Set up Docker entrypoint script
WORKDIR /repo/apps/frontend

# Set production environment
ENV NODE_ENV=production

# Expose the port the app will run on
EXPOSE 3000

# Set the entrypoint
ENTRYPOINT ["./docker-entrypoint.sh"]
With entrypoint:
#!/bin/sh

# Build the application with environment variables
echo "Building application..."
bun run build

# Start the application
echo "Starting application..."
exec bun run start
#!/bin/sh

# Build the application with environment variables
echo "Building application..."
bun run build

# Start the application
echo "Starting application..."
exec bun run start
This allows me to pass environment variables as part of the run args at the expense of a slower startup. Correct way to do this is clearly to build with the runtime args first (like in hosted environments such as Netlify and Vercel where you can set build args per deployment), but this at least solves my immediate issue
flat-fuchsia
flat-fuchsiaOP6mo ago
Update again, ended up not doing this and going with build args in Docker, more here: https://docs.docker.com/build/building/variables/
Docker Documentation
Variables
Using build arguments and environment variables to configure builds

Did you find this page helpful?