Vite Build using Dockerfile: Environment Variables Undefined

webvelocityzaHOBBY

8 months ago

BACKGROUND

I have a project which I deployed to Railway. It consists of a VITE+REACT frontend and a node server.

During the build, the frontend files are deployed to server/public and served from there.

PROBLEM:

The node server works well using process.env. The VITE build has all variables undefined. Please help.

File Structure

project-root/
├── frontend/
│   ├── public/
│   ├── src/
│   │   ├── assets/
│   │   ├── components/
│   │   ├── pages/
│   │   ├── App.tsx
│   │   ├── main.tsx
│   │   ├── config.ts
│   │   └── ...
│   ├── .env
│   ├── index.html
│   ├── package.json
│   ├── tsconfig.json
│   ├── vite.config.ts
│   └── ...
├── server/
│   ├── controllers/
│   ├── models/
│   ├── routes/
│   ├── index.js
│   ├── package.json
│   ├── .env
│   └── ...
├── .env
├── Dockerfile
├── package.json
├── package-lock.json
└── README.md

Dockerfile

# Use an official Node runtime as the base image
FROM node:18

ENV NPM_CONFIG_UPDATE_NOTIFIER=false
ENV NPM_CONFIG_FUND=false
ENV NODE_ENV=production

# Set the working directory in the container
WORKDIR /

# Copy package.json and package-lock.json for both server and frontend
COPY package*.json ./
COPY frontend/package*.json ./frontend/
COPY server/package*.json ./server/

# Install dependencies
RUN npm install && \
    cd frontend && npm install && cd .. && \
    cd server && npm install && cd ..

# Copy the rest of the application code
COPY . .

# Environment variables for Vite and Node.js runtime
ARG VITE_API_SERVER_URL
ARG VITE_SUPABASE_URL
ARG VITE_SUPABASE_ANON_KEY
ARG VITE_SENTRY_ORG
ARG VITE_SENTRY_PROJECT_ID
ARG VITE_SENTRY_AUTH_TOKEN

# Build the frontend
RUN cd frontend && npm run build

# Expose the port the app runs on
EXPOSE 8080

# Command to run the application
CMD ["node", "server/index.js"]

VITE config

export default defineConfig(() => {
  return {
    plugins: [
      react(),
    ],
    envDir: path.resolve(__dirname, ".."), // locally we have .env file in root
    build: {
      outDir: "../server/public",
      emptyOutDir: false,
    }
    ...
  };
});
Solved

2 Replies

8 months ago

Try removing envDir from your vite config file.


webvelocityzaHOBBY

8 months ago

I swear I spent 8hrs on this issue. Thanks a lot. It worked


Status changed to Solved brody 8 months ago


Vite Build using Dockerfile: Environment Variables Undefined - Railway Help Station