How to host backend API within Vite configured for React #20506
Unanswered
adam-nielsen
asked this question in
Q&A
Replies: 0 comments
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.ts
and then using a custom plugin to ultimately callserver.middlewares.use()
so that my API code gets called to handle the/api
URL.This all works fine, but I can't use
import.meta.env
in my backend code, HMR is unreliable, and typos in my backend code cause Vite to terminate. Reading up on it, theimport.meta.env
issue seems to be because Vite doesn't load the.env
file until after it has finished processing the config, so since I'm importing code invite.config.ts
it's running beforeimport.meta.env
is 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.env
is available, crashes don't terminate Vite, etc.)Beta Was this translation helpful? Give feedback.
All reactions