ashutosh887
ashutosh887

Reputation: 1029

How to add Environment Variables in vite.config.js for a React Project

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!

Upvotes: 5

Views: 28141

Answers (5)

Ferdaus Zaman Polok
Ferdaus Zaman Polok

Reputation: 117

Anyone who is using Vite 4.0 and process.env = { ...process.env, ...loadEnv(mode, process.cwd()) }; is not working for you try this:

First Install dotenv using yarn add dotenv. Then go to your vite.config.js file write these:

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

dotenv.config();

console.log("hello", process.env.VITE_HOMEPAGE_URL) //when you run the frontend using yarn dev you will be able to see this on you cmd to know this works! :D

export default defineConfig({
  base: process.env.VITE_HOMEPAGE_URL,
  plugins: [react()],
})

Your environment variable file .env should look something like this:

VITE_HOMEPAGE_URL=https://abc.something.com/home/

If you face linter error like process is not defined go to your .eslintrc.cjs file and add node: true inside the env. So it will look something like below

module.exports = {
  env: { browser: true, es2020: true, node: true },
  //...other settings
}

Upvotes: 4

Tharindu Jayasanka
Tharindu Jayasanka

Reputation: 359

I had exactly same issue and found a solution:

import { defineConfig, loadEnv } from 'vite';

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

  const API_URL = `${env.VITE_API_URL ?? 'http://localhost:3000'}`;
  //or leave it empty const API_URL = `${env.VITE_API_URL ?? ''}`;

  return {
    server: {
      proxy: {
        '/api': {
          target: API_URL,
          changeOrigin: true,
          rewrite: (path) => path.replace(/^\/api/, ''),
        },
      },
    },
    plugins: [react()],
  };
});

In .env

VITE_API_URL=https://your-api-url.com

Upvotes: 2

Samanja Cartagena
Samanja Cartagena

Reputation: 148

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

Upvotes: 5

Saeid Doroudi
Saeid Doroudi

Reputation: 1245

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

Upvotes: 11

Samanja Cartagena
Samanja Cartagena

Reputation: 148

 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=>{})

Upvotes: 1

Related Questions