VITE envs with REACTJS

lucaimbalzanoHOBBY

8 months ago

idk why it doesn't take my env variables

so i have my .env with:

VITE_FIREBASE_API_KEY_O=TOKEN
VITE_FIREBASE_AUTHDOMAIN=TOKEN

and 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.js

import { defineConfig, loadEnv } from "vite";
import react from "@vitejs/plugin-react-swc";

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: 5173,
    },
    plugins: [react()],
    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),
    },
  };
});

so if i do a little external console.log i have undefined:

import { initializeApp } from "firebase/app";
// i tried this console log with my define in defineConfig
console.log(` VITE_FIREBASE_API_KEY: ${VITE_FIREBASE_API_KEY}`);

console.log(` VITE_FIREBASE_API_KEY: ${import.meta.env.VITE_FIREBASE_API_KEY}`);
// You can now directly use these constants
const firebaseConfig = {
  apiKey: VITE_FIREBASE_API_KEY,
  authDomain: VITE_FIREBASE_AUTHDOMAIN,
  projectId: VITE_FIREBASE_PROJECT_ID,
  storageBucket: VITE_FIREBASE_STORAGE_BUCKET,
  messagingSenderId: VITE_FIREBASE_MESSAGING_SENDER_ID,
  appId: VITE_FIREBASE_APP_ID,
};

console.log('FIREBASECONFIG:', firebaseConfig); // This should log your Firebase configuration with correct values.

export const firebaseApp = initializeApp(firebaseConfig);

5 Replies

lucaimbalzanoHOBBY

8 months ago

This is my actual situation with envs in railway:

this is my tree app:
╭─░▒▓    ~/Doc/Workspaces/Private/houseav-workspace/github.organization/houseav.frontend  on   main !6 ▓▒░ ░▒▓  at 22:50:28  ▓▒░

╰─ tree -I 'node_modules'

.

├── Dockerfile

├── Dockerfile.nginix

├── README.md

├── dist

│ ├── assets

│ │ ├── ad-BOo-tPI4.svg

│ │ ├── ad-CDtWnnSA.svg

│ ├── index.html

│ └── roomHomePage2.png

├── index.html

├── package-lock.json

├── package.json

├── postcss.config.js

├── public

│ └── roomHomePage2.png

├── src

│ ├── App.jsx

│ ├── assets

│ │ ├── default-house-photo.png

│ │ ├── default-user-profile-photo.png

│ │ ├── google.svg

│ │ ├── home.png

│ │ ├── notfound.svg

│ │ ├── spinner-loading.gif

│ │ └── spinner-safe.gif

│ ├── components

│ │ ├── Badge.jsx

│ │ ├── Button

│ │ │ ├── RippleButton.css

│ │ │ └── RippleButton.jsx

│ │ ├── Contact.jsx

│ │ ├── Footer.jsx

│ │ ├── Header.jsx

│ │ ├── Input

│ │ │ ├── FloatingLabelInput.css

│ │ │ ├── FloatingLabelnput.jsx

│ │ │ ├── InputSelectNumberPrefix.jsx

│ │ │ └── InputToolTip.jsx

│ │ ├── ListingItem.jsx

│ │ ├── Modal.jsx

│ │ ├── Notification.jsx

│ │ ├── OAuth.jsx

│ │ ├── PrivateRoute.jsx

│ │ ├── SearchFilter

│ │ │ └── SearchFilter.jsx

│ │ ├── SelectOptions.jsx

│ │ ├── Spinner.jsx

│ │ ├── Stepper

│ │ │ ├── Stepper.jsx

│ │ │ ├── StepperPreline.jsx

│ │ │ ├── stepper.css

│ │ │ └── validations.js

│ │ ├── Toggle.jsx

│ │ ├── Translations

│ │ │ └── TranslationsSelection.jsx

│ │ ├── YourListing.jsx

│ │ ├── bg-pattern

│ │ │ ├── animated-grid-pattern

│ │ │ │ └── AnimatedGridPattern.jsx

│ │ │ └── dot-pattern

│ │ │ └── DotPattern.jsx

│ │ └── text

│ │ └── scroll-based-velocity

│ │ └── ScrollBasedVelocity.jsx

│ ├── firebase.js

│ ├── hooks

│ │ └── useWindowSize.js

│ ├── i18n

│ │ ├── i18n.js

│ │ └── locales

│ │ ├── en

│ │ │ └── common.json

│ │ ├── es

│ │ │ └── common.json

│ │ ├── fr

│ │ │ └── common.json

│ │ ├── it

│ │ │ └── common.json

│ │ └── pt

│ │ └── common.json

│ ├── index.css

│ ├── main.jsx

│ ├── pages

│ │ ├── About.jsx

│ │ ├── CreateListing.jsx

│ │ ├── Dashboard

│ │ │ ├── AdminUpdateHouse.jsx

│ │ │ ├── AdminUpdateProfile.jsx

│ │ │ ├── AdminViewReferralLetter.jsx

│ │ │ ├── Dashboard.jsx

│ │ │ ├── QueueListing.jsx

│ │ │ └── QueueRegister.jsx

│ │ ├── ForgotPassword.jsx

│ │ ├── ForgotPasswordRequest.jsx

│ │ ├── Home.jsx

│ │ ├── Listing.jsx

│ │ ├── ListingInReview.jsx

│ │ ├── NotFound.jsx

│ │ ├── Profile

│ │ │ ├── PendingProfile.jsx

│ │ │ ├── Profile.jsx

│ │ │ ├── ProfileInReview.jsx

│ │ │ ├── ProfileReviewed.jsx

│ │ │ └── handleFunctions.js

│ │ ├── Search.jsx

│ │ ├── SignIn.jsx

│ │ ├── SignUp.jsx

│ │ ├── UpdateListing.jsx

│ │ └── custom.css

│ └── redux

│ ├── language

│ │ └── languageSlice.js

│ ├── store.js

│ └── user

│ └── userSlice.js

├── tailwind.config.js

├── utils

│ ├── country_prefixes.json

│ ├── security_en_de.js

│ └── utils.js

└── vite.config.js

32 directories, 237 files

Attachments



lucaimbalzanoHOBBY

8 months ago

of course i did not share with you my dockerfile..
actually i saw a response that use caddy:
here the answer i am taking inspiration: https://help.railway.app/questions/vite-app-import-meta-env-vite-apu-url-i-93f87706
i copied the Caddyfile how the suggest: https://github.com/brody192/vite-react-template

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:3000} {

	# access logs

	log {

		format json # set access log format to json mode

	}

	# 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

}

Dockerfile:

# Build Stage
FROM node:18-slim AS build

ENV NPM_CONFIG_UPDATE_NOTIFIER=false
ENV NPM_CONFIG_FUND=false

WORKDIR /app

COPY package*.json ./

RUN npm ci

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

# 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}

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 /srv

CMD ["caddy", "run", "--config", "/etc/caddy/Caddyfile", "--adapter", "caddyfile"]

so now it goes up and the logger looks like that:
the problem is that i cannot reach the frontend... railway give me an error ->

Application failed to respond

This error appears to be caused by the application.

i changed also the port on my vite.config.js:

    preview: {
      port: 3000,
    },

Logger on Railway:
Build time: 32.01 seconds

Starting Container

2024-09-03T13:14:59.456491141Z [INFO] using config from file file="/etc/caddy/Caddyfile" ts=1725369298.1384234

2024-09-03T13:14:59.456508972Z [INFO] adapted config to JSON adapter="caddyfile" ts=1725369298.1411684

2024-09-03T13:14:59.456529661Z [WARN] Caddyfile input is not formatted; run 'caddy fmt --overwrite' to fix inconsistencies adapter="caddyfile" file="/etc/caddy/Caddyfile" line=37 ts=1725369298.1411924

2024-09-03T13:14:59.456546735Z [WARN] admin endpoint disabled logger="admin" ts=1725369298.1414268

2024-09-03T13:14:59.456565535Z [INFO] started background certificate maintenance cache="0xc0004f8a80" logger="tls.cache.maintenance" ts=1725369298.1416335

2024-09-03T13:14:59.456583649Z [INFO] automatic HTTPS is completely disabled for server logger="http.auto_https" server_name="srv0" ts=1725369298.1423593

2024-09-03T13:14:59.456601095Z [INFO] cleaning storage unit logger="tls" storage="FileStorage:/data/caddy" ts=1725369298.145826

2024-09-03T13:14:59.456619387Z [INFO] server running logger="http.log" name="srv0" protocols=["h1","h2","h3"] ts=1725369298.145423

2024-09-03T13:14:59.456633949Z [INFO] serving initial configuration ts=1725369298.1460664

2024-09-03T13:14:59.456667582Z [INFO] finished cleaning storage units logger="tls" ts=1725369298.1460414


8 months ago

Now that you are using Caddy, any vite server config would be irrelevant.

Your domain is likely pointing to the incorrect port, you can click the edit icon on your domain and then select the port with the caddy label.


lucaimbalzanoHOBBY

8 months ago

Like this?
... i still have 502 Bad Gateway

Deploy Logs:
Starting Container

Sep 03 15:19:51

using config from file

Sep 03 15:19:51

adapted config to JSON

Sep 03 15:19:51

Caddyfile input is not formatted; run 'caddy fmt --overwrite' to fix inconsistencies

Sep 03 15:19:51

admin endpoint disabled

Sep 03 15:19:51

automatic HTTPS is completely disabled for server

Sep 03 15:19:51

started background certificate maintenance

Sep 03 15:19:51

server running

Sep 03 15:19:51

serving initial configuration

Sep 03 15:19:51

cleaning storage unit

Sep 03 15:19:51

finished cleaning storage units

Attachments


VITE envs with REACTJS - Railway Help Station