How to host backend API within Vite configured for React #20506
Replies: 2 comments 2 replies
-
|
I dont think importing your actual backend app into From what you described, it works, but it also explains all the weird side effects:
So I’d probly treat this as:
So the cleaner setup is usually:
That way:
Trying to make backend application code live inside the Vite config ends up mixing 2 different responsibilities:
If your goal is “same port for the browser”, the proxy still gives you that developer experience without forcing both runtimes into the same execution path. So my short answer would be:
If you really want a single command to start both, I’d still do it as two processes launched together, not one process with the backend embedded into Vite. If this helps, feel free to mark it as the answer so others can find it faster. |
Beta Was this translation helpful? Give feedback.
-
|
The Vite docs point toward keeping these as separate responsibilities:
Vite already has first-class support for this pattern via: export default defineConfig({
server: {
proxy: {
'/api': {
target: 'http://localhost:3000',
changeOrigin: true,
},
},
},
})That matches the problems you're seeing with importing backend runtime code into
So I don't think the "best" shape is to make one Vite instance be your backend runtime. The cleaner setup is:
If you want a single command, I'd still orchestrate two processes rather than embedding the backend inside the Vite config. |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
-
I have Vite working with a React frontend. I would like the same Vite instance to also serve the NodeJS backend.
I have done this by importing my backend code in
vite.config.tsand then using a custom plugin to ultimately callserver.middlewares.use()so that my API code gets called to handle the/apiURL.This all works fine, but I can't use
import.meta.envin my backend code, HMR is unreliable, and typos in my backend code cause Vite to terminate. Reading up on it, theimport.meta.envissue seems to be because Vite doesn't load the.envfile until after it has finished processing the config, so since I'm importing code invite.config.tsit's running beforeimport.meta.envis available. This suggests that importing application code in the Vite config file is not the correct way to have it handle new URLs.So my question is what is the best way to have my Node backend API run in the same Vite instance as the React frontend, such that the backend code is treated the same as the frontend (i.e.
import.meta.envis available, crashes don't terminate Vite, etc.)Beta Was this translation helpful? Give feedback.
All reactions