2

How can I add Environment Variables in Vite React Project in the vite.config.js file

I wanted to add the proxy_url in the .env file and add it to the environment when deploying. Please have a look below!

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

const proxy_url = "http://localhost:5000/";

export default defineConfig({
  plugins: [react()],
  server: {
    proxy: {
      "/api": {
        target: proxy_url,
        changeOrigin: true,
        rewrite: (path) => path.replace(/^/api/, ""),
      },
    },
  },
});

Some blogs and answers on StackOverflow but they were resolving the same issue for Vue. Those didn't work for me in my Vite-React Project!

ashutosh887
  • 361
  • 3
  • 11

3 Answers3

5

you can use it in this way:

install "cross-env" package and config vite

import { defineConfig, loadEnv } from 'vite'

export default defineConfig(({ mode }) => {
  const env = loadEnv(mode, process.cwd(), '')

  return {
    define: {
      __APP_ENV__: env.APP_ENV,
    },

    // rest of Vite config
  }
}

to use in your code you can do in this way:

import.meta.env.VariableName

update: according to Vite documentation, environment variables should start with VITE_ prefix to get known

for example in .env file:

VITE_BASE_API_URL=http://localhost:5000

to use it :

import.meta.env.VITE_BASE_API_URL
Saeid Doroudi
  • 935
  • 1
  • 9
  • 25
3

This will work. Get a .env file and than make your vite.config.js file like this

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

// https://vitejs.dev/config/
export default defineConfig(({mode}) => {
  const env = loadEnv(mode, process.cwd());

  return {
    plugins: [react()],
    build: {
      outDir: "./wwwroot/app/",
      sourcemap: true,
    },
    server: {
      port: env.VITE_PORT,
    },
  };
});

This is my .env file. You dont have to install anything extra

VITE_PORT=3000
Gangadhar Jannu
  • 4,136
  • 6
  • 29
  • 49
  • Thanks. But I'm trying to target the PROXY_URL (for Backend) but don't want to expose it on the Code (use as env variable) and not the PORT on which the Application should run :( – ashutosh887 Jan 30 '23 at 05:18
1
 import { defineConfig, loadEnv } from 'vite'
 import vue from '@vitejs/plugin-vue'

   export default defineConfig(({mode})=>{
 const env = loadEnv(mode, process.cwd());

return{
plugins: [react()],
build:{
   outDir:"./wwwroot/app/", sourcemap:true
 },
  server: {

proxy: {
  "^/api": {
    target:env.VITE_PORT,
    
    changeOrigin: true,
    secure: false,
    withCredentials: true,
    rewrite: (path) => path.replace(/^\/api/, ``),
  },   
   
},
   port:4000
 }
}
})

Than, you can call it by api

  async fetchdata(){
     
  await  axios.get(`/api/${mainPage}`,{
 
 }
).then(response=>{})