Questions icon indicating copy to clipboard operation
Questions copied to clipboard

Vite config file issue

Open Gaurav-Wagh1 opened this issue 1 year ago • 0 comments

I have a .env file which contains my backend server endpoint. I have configured vite.config.js file to use that endpoint from .env file. But as I have added it on vercel for production, my project is facing some issue to hit the url through proxy.

My vite.config.js file

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

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

My App.jsx file

import axios from 'axios'

function App() {

  const fetchdata = async() => {
    try {
      console.log(import.meta.env.VITE_URL);           // working well on deployment;
      
      const res = await axios.get("/api/users");       // throwing error on deployment
      console.log(res)

    } catch (error) {
      console.log(error)
    }
  }
  fetchdata();

  return (
    <>
       <h1>Hello world</h1>
    </>
  )
}

export default App

All the code is working well in my local system on npm run dev but showing error on deployment on vercel and netlify. When I am trying to do console.log(import.meta.env.VITE_URL) in my App.jsx file my server endpoint is successfully printing on console, but axios request is throwing error. That means this environment variables are accessible at App.jsx file but there may be some issue at vite.config.js. Please help me

Gaurav-Wagh1 avatar May 25 '24 08:05 Gaurav-Wagh1