env vite reactjs

Hey guys, i tried everything but i cannot get my env variables on my vite app. here my track conversation: https://help.railway.app/questions/vite-envs-with-reactjs-49ea0fd4 i also tried the nixpack.toml way, but did not work
Railway Help Station
VITE envs with REACTJS
idk why it doesn't take my env variablesso i have my .env with:VITE_FIREBASE_API_KEY_O=TOKEN VITE_FIREBASE_AUTHDOMAIN=TOKENand my railway have env setup the same..i tried to get them in a lot of ways:- by simply using import.meta.env.VITE_FIREBASE_API_KEY_O- or in my vite.config.jsimport { defineConfig, loadEnv } from "vite"; import react from "...
25 Replies
Percy
Percy3mo ago
Project ID: 0bebe0c6-57e2-4755-93c3-ce48f433731b
lucaimbalzano
lucaimbalzanoOP3mo ago
0bebe0c6-57e2-4755-93c3-ce48f433731b
Brody
Brody3mo ago
hey, please dont cross post, if you feel like i have dropped the ball in your thread, feel free to bump it, but please dont create duplicate threads.
lucaimbalzano
lucaimbalzanoOP3mo ago
okok, i just posted here because i saw quick answers, any help with that thread?
Brody
Brody3mo ago
im typing in that thread as we speak, but you are right, discord is a more chat oriented place, if you want to swap to discrd for support that is fine with me
lucaimbalzano
lucaimbalzanoOP3mo ago
let is swap do you think i need to rewrite everything?
Brody
Brody3mo ago
well currently your build is failing, you should look at your build logs and make the needed fixes to at least get it to build before we worry about environment variables
lucaimbalzano
lucaimbalzanoOP3mo ago
it is failing because i am trying to fix that errors
Brody
Brody3mo ago
sounds good, please get your build building before we worry about environment variables
lucaimbalzano
lucaimbalzanoOP3mo ago
hey @Brody now is up, i think i made a success deploy with caddy i had problem to understand on how i need to place the endpoints as i did in my vite.config.js before
Brody
Brody3mo ago
endpoints?
lucaimbalzano
lucaimbalzanoOP3mo ago
these endpoints:
import { defineConfig, loadEnv } from "vite";

export default defineConfig(({ mode }) => {
// Load environment variables based on the current mode
const env = loadEnv(mode, process.cwd());

// Define your BASE_API_URL using the environment variable or fallback to localhost
const BASE_API_URL = `${env.VITE_ENDPOINT_API_V1 ?? "http://localhost:3000"}`;

return {
server: {
origin: BASE_API_URL,
proxy: {
"/auth": {
target: BASE_API_URL,
secure: false,
changeOrigin: true,
logLevel: "debug",
},
// ... other proxies
},
},
preview: {
port: 3000,
},
define: {
VITE_FIREBASE_API_KEY: JSON.stringify(env.VITE_FIREBASE_API_KEY),
VITE_FIREBASE_AUTHDOMAIN: JSON.stringify(env.VITE_FIREBASE_AUTHDOMAIN),
VITE_FIREBASE_PROJECT_ID: JSON.stringify(env.VITE_FIREBASE_PROJECT_ID),
VITE_FIREBASE_STORAGE_BUCKET: JSON.stringify(
env.VITE_FIREBASE_STORAGE_BUCKET
),
VITE_FIREBASE_MESSAGING_SENDER_ID: JSON.stringify(
env.VITE_FIREBASE_MESSAGING_SENDER_ID
),
VITE_FIREBASE_APP_ID: JSON.stringify(env.VITE_FIREBASE_APP_ID),
},
build: {
rollupOptions: {
assetsInclude: ["**/*.node"],
external: ["fsevents", "@swc/core", "@swc/wasm"],
},
},
};
});

}
import { defineConfig, loadEnv } from "vite";

export default defineConfig(({ mode }) => {
// Load environment variables based on the current mode
const env = loadEnv(mode, process.cwd());

// Define your BASE_API_URL using the environment variable or fallback to localhost
const BASE_API_URL = `${env.VITE_ENDPOINT_API_V1 ?? "http://localhost:3000"}`;

return {
server: {
origin: BASE_API_URL,
proxy: {
"/auth": {
target: BASE_API_URL,
secure: false,
changeOrigin: true,
logLevel: "debug",
},
// ... other proxies
},
},
preview: {
port: 3000,
},
define: {
VITE_FIREBASE_API_KEY: JSON.stringify(env.VITE_FIREBASE_API_KEY),
VITE_FIREBASE_AUTHDOMAIN: JSON.stringify(env.VITE_FIREBASE_AUTHDOMAIN),
VITE_FIREBASE_PROJECT_ID: JSON.stringify(env.VITE_FIREBASE_PROJECT_ID),
VITE_FIREBASE_STORAGE_BUCKET: JSON.stringify(
env.VITE_FIREBASE_STORAGE_BUCKET
),
VITE_FIREBASE_MESSAGING_SENDER_ID: JSON.stringify(
env.VITE_FIREBASE_MESSAGING_SENDER_ID
),
VITE_FIREBASE_APP_ID: JSON.stringify(env.VITE_FIREBASE_APP_ID),
},
build: {
rollupOptions: {
assetsInclude: ["**/*.node"],
external: ["fsevents", "@swc/core", "@swc/wasm"],
},
},
};
});

}
in this case it understand base_url/auth
Brody
Brody3mo ago
imo, using a proxy here is a terrible practice, ive only ever seen user's have trouble with it when they go to run their app in a production environment. you can rip all the proxy stuff out, then for example, instead of calling /auth you call <backend url from environment variable> + "/auth"
lucaimbalzano
lucaimbalzanoOP3mo ago
i have problems gettings envs.. and now i cannot reach the endpoind after deploy, i have 502 error here my actual Docker file
# Build Stage
FROM node:latest AS build

ENV NPM_CONFIG_UPDATE_NOTIFIER=false
ENV NPM_CONFIG_FUND=false

WORKDIR /app

COPY package*.json ./

RUN npm install

COPY . ./

# Define ARGs for each of your Firebase environment variables
ARG VITE_FIREBASE_API_KEY
ARG VITE_FIREBASE_AUTHDOMAIN
ARG VITE_FIREBASE_PROJECT_ID
ARG VITE_FIREBASE_STORAGE_BUCKET
ARG VITE_FIREBASE_MESSAGING_SENDER_ID
ARG VITE_FIREBASE_APP_ID
ARG VITE_ENDPOINT_API

# Pass ARG values to the build process
ENV VITE_FIREBASE_API_KEY=${VITE_FIREBASE_API_KEY}
ENV VITE_FIREBASE_AUTHDOMAIN=${VITE_FIREBASE_AUTHDOMAIN}
ENV VITE_FIREBASE_PROJECT_ID=${VITE_FIREBASE_PROJECT_ID}
ENV VITE_FIREBASE_STORAGE_BUCKET=${VITE_FIREBASE_STORAGE_BUCKET}
ENV VITE_FIREBASE_MESSAGING_SENDER_ID=${VITE_FIREBASE_MESSAGING_SENDER_ID}
ENV VITE_FIREBASE_APP_ID=${VITE_FIREBASE_APP_ID}
ENV VITE_ENDPOINT_API=${VITE_ENDPOINT_API}

RUN npm run build

# Serve Stage
FROM caddy:latest

WORKDIR /app

COPY Caddyfile /etc/caddy/Caddyfile

# Copy the build output from the build stage to the serve stage
COPY --from=build /app/dist /app/dist

EXPOSE 5173

CMD ["caddy", "run", "--config", "/etc/caddy/Caddyfile", "--adapter", "caddyfile"]
# Build Stage
FROM node:latest AS build

ENV NPM_CONFIG_UPDATE_NOTIFIER=false
ENV NPM_CONFIG_FUND=false

WORKDIR /app

COPY package*.json ./

RUN npm install

COPY . ./

# Define ARGs for each of your Firebase environment variables
ARG VITE_FIREBASE_API_KEY
ARG VITE_FIREBASE_AUTHDOMAIN
ARG VITE_FIREBASE_PROJECT_ID
ARG VITE_FIREBASE_STORAGE_BUCKET
ARG VITE_FIREBASE_MESSAGING_SENDER_ID
ARG VITE_FIREBASE_APP_ID
ARG VITE_ENDPOINT_API

# Pass ARG values to the build process
ENV VITE_FIREBASE_API_KEY=${VITE_FIREBASE_API_KEY}
ENV VITE_FIREBASE_AUTHDOMAIN=${VITE_FIREBASE_AUTHDOMAIN}
ENV VITE_FIREBASE_PROJECT_ID=${VITE_FIREBASE_PROJECT_ID}
ENV VITE_FIREBASE_STORAGE_BUCKET=${VITE_FIREBASE_STORAGE_BUCKET}
ENV VITE_FIREBASE_MESSAGING_SENDER_ID=${VITE_FIREBASE_MESSAGING_SENDER_ID}
ENV VITE_FIREBASE_APP_ID=${VITE_FIREBASE_APP_ID}
ENV VITE_ENDPOINT_API=${VITE_ENDPOINT_API}

RUN npm run build

# Serve Stage
FROM caddy:latest

WORKDIR /app

COPY Caddyfile /etc/caddy/Caddyfile

# Copy the build output from the build stage to the serve stage
COPY --from=build /app/dist /app/dist

EXPOSE 5173

CMD ["caddy", "run", "--config", "/etc/caddy/Caddyfile", "--adapter", "caddyfile"]
lucaimbalzano
lucaimbalzanoOP3mo ago
Here my actual caddyfile:
# global options
{
admin off # theres no need for the admin api in railway's environment
persist_config off # storage isn't persistent anyway
auto_https off # railway handles https for us, this would cause issues if left enabled
# runtime logs
log {
format json # set runtime log format to json mode
}
# server options
servers {
trusted_proxies static private_ranges 100.0.0.0/8 # trust railway's proxy
}
}

# site block, listens on the $PORT environment variable, automatically assigned by railway
:{$PORT:5173} {
# access logs
log {
# format json # set access log format to json mode
output stdout # Print logs to standard output
format console # Use a human-readable log format
}

# health check for railway
rewrite /health /*

# serve from the 'dist' folder (Vite builds into the 'dist' folder)
root * dist

# enable gzipping responses
encode gzip

# serve files from 'dist'
file_server

# if path doesn't exist, redirect it to 'index.html' for client side routing
try_files {path} /index.html
}
# global options
{
admin off # theres no need for the admin api in railway's environment
persist_config off # storage isn't persistent anyway
auto_https off # railway handles https for us, this would cause issues if left enabled
# runtime logs
log {
format json # set runtime log format to json mode
}
# server options
servers {
trusted_proxies static private_ranges 100.0.0.0/8 # trust railway's proxy
}
}

# site block, listens on the $PORT environment variable, automatically assigned by railway
:{$PORT:5173} {
# access logs
log {
# format json # set access log format to json mode
output stdout # Print logs to standard output
format console # Use a human-readable log format
}

# health check for railway
rewrite /health /*

# serve from the 'dist' folder (Vite builds into the 'dist' folder)
root * dist

# enable gzipping responses
encode gzip

# serve files from 'dist'
file_server

# if path doesn't exist, redirect it to 'index.html' for client side routing
try_files {path} /index.html
}
This is my env port setup on railway:
No description
lucaimbalzano
lucaimbalzanoOP3mo ago
@Brody and this have no sense:
import React, { useEffect, useState } from "react";
import { Link, useNavigate } from "react-router-dom";
import { useDispatch, useSelector } from "react-redux";
import { useTranslation } from "react-i18next";

import {
signInStart,
signInSuccess,
signInFailure,
} from "../redux/user/userSlice";

import Spinner from "../components/Spinner";
import FloatingLabelInput from "../components/Input/FloatingLabelnput";

export default function SignIn() {
const BASE_URL = import.meta.VITE_ENDPOINT_API;
console.log(
`VITE CONFIG BASE URL: ${BASE_URL}`,
import.meta.env.VITE_FIREBASE_API_KEY_O,
import.meta.env.VITE_USER_QUEUE_REGISTRATION
);


...
import React, { useEffect, useState } from "react";
import { Link, useNavigate } from "react-router-dom";
import { useDispatch, useSelector } from "react-redux";
import { useTranslation } from "react-i18next";

import {
signInStart,
signInSuccess,
signInFailure,
} from "../redux/user/userSlice";

import Spinner from "../components/Spinner";
import FloatingLabelInput from "../components/Input/FloatingLabelnput";

export default function SignIn() {
const BASE_URL = import.meta.VITE_ENDPOINT_API;
console.log(
`VITE CONFIG BASE URL: ${BASE_URL}`,
import.meta.env.VITE_FIREBASE_API_KEY_O,
import.meta.env.VITE_USER_QUEUE_REGISTRATION
);


...
when i run my docker container in localhost i see VITE_FIREBASE_API_KEY_O and VITE_USER_QUEUE_REGISTRATION but not my VITE_ENDPOINT_API (it is undefined)
Brody
Brody3mo ago
can you send your vite config again
lucaimbalzano
lucaimbalzanoOP3mo ago
is this one:
import { defineConfig, loadEnv } from "vite";

export default defineConfig(({ mode }) => {
const env = loadEnv(mode, process.cwd());
const BASE_API_URL = `${env.VITE_ENDPOINT_API_V1 ?? "http://localhost:3000"}`;
console.log(`vote.config.js::BASE_API_URL: ${BASE_API_URL}, mode: ${mode}`);
return {
server: {
origin: BASE_API_URL,
proxy: {
"/auth": {
target: BASE_API_URL,
secure: false,
changeOrigin: true,
logLevel: "debug",
},
"/house": {
target: BASE_API_URL,
secure: false,
changeOrigin: true,
logLevel: "debug",
},
.... All endpoints...
"/forgot-password/check": {
target: BASE_API_URL,
secure: false,
changeOrigin: true,
logLevel: "debug",
},
},
},
preview: {
port: 5173,
},
define: {
VITE_FIREBASE_API_KEY: JSON.stringify(env.VITE_FIREBASE_API_KEY),
VITE_FIREBASE_AUTHDOMAIN: JSON.stringify(env.VITE_FIREBASE_AUTHDOMAIN),
VITE_FIREBASE_PROJECT_ID: JSON.stringify(env.VITE_FIREBASE_PROJECT_ID),
VITE_FIREBASE_STORAGE_BUCKET: JSON.stringify(
env.VITE_FIREBASE_STORAGE_BUCKET
),
VITE_FIREBASE_MESSAGING_SENDER_ID: JSON.stringify(
env.VITE_FIREBASE_MESSAGING_SENDER_ID
),
VITE_FIREBASE_APP_ID: JSON.stringify(env.VITE_FIREBASE_APP_ID),
},
build: {
rollupOptions: {
assetsInclude: ["**/*.node"],
external: ["fsevents", "@swc/core", "@swc/wasm"],
},
},
};
});
import { defineConfig, loadEnv } from "vite";

export default defineConfig(({ mode }) => {
const env = loadEnv(mode, process.cwd());
const BASE_API_URL = `${env.VITE_ENDPOINT_API_V1 ?? "http://localhost:3000"}`;
console.log(`vote.config.js::BASE_API_URL: ${BASE_API_URL}, mode: ${mode}`);
return {
server: {
origin: BASE_API_URL,
proxy: {
"/auth": {
target: BASE_API_URL,
secure: false,
changeOrigin: true,
logLevel: "debug",
},
"/house": {
target: BASE_API_URL,
secure: false,
changeOrigin: true,
logLevel: "debug",
},
.... All endpoints...
"/forgot-password/check": {
target: BASE_API_URL,
secure: false,
changeOrigin: true,
logLevel: "debug",
},
},
},
preview: {
port: 5173,
},
define: {
VITE_FIREBASE_API_KEY: JSON.stringify(env.VITE_FIREBASE_API_KEY),
VITE_FIREBASE_AUTHDOMAIN: JSON.stringify(env.VITE_FIREBASE_AUTHDOMAIN),
VITE_FIREBASE_PROJECT_ID: JSON.stringify(env.VITE_FIREBASE_PROJECT_ID),
VITE_FIREBASE_STORAGE_BUCKET: JSON.stringify(
env.VITE_FIREBASE_STORAGE_BUCKET
),
VITE_FIREBASE_MESSAGING_SENDER_ID: JSON.stringify(
env.VITE_FIREBASE_MESSAGING_SENDER_ID
),
VITE_FIREBASE_APP_ID: JSON.stringify(env.VITE_FIREBASE_APP_ID),
},
build: {
rollupOptions: {
assetsInclude: ["**/*.node"],
external: ["fsevents", "@swc/core", "@swc/wasm"],
},
},
};
});
i think it is sad because in localhost is working and in production not..
Brody
Brody3mo ago
as previously mentioned, please remove the proxy stuff and also the define stuff while you're at it
lucaimbalzano
lucaimbalzanoOP3mo ago
Hey @Brody many thanks for your patience, i still have my envs undefined .. but you know what God is good also while my envs are undefined
Brody
Brody3mo ago
send me your new config file
lucaimbalzano
lucaimbalzanoOP3mo ago
@Brody fixed, the problem were how i was pulling envs so the process is: - make sure it is taking the right .env file - add envs in your service in railway - add them also as ENV & ARG - depending on your webserver pull envs (process.env, import.meta.env,....) thank you brother
Brody
Brody3mo ago
you arent using .env files in prod right?
lucaimbalzano
lucaimbalzanoOP3mo ago
yes i am using them and i was using them
Brody
Brody3mo ago
please never use .env files in prod, thats a horrible practice
Want results from more Discord servers?
Add your server