This feels like a dumb question but I'm stumped so here it is:
I have built a MERN stack app but can't figure out how I would deploy it and maintain functionality. Currently, I have a client
directory which contains my react code and a server
directory which contains my server code. The server is running on my local machine at port 4000. When I start up the server using the CLI, it connects to MongoDB Atlas and then any fetch requests to http://localhost:4000
from the frontend are handled correctly. The client is currently running on port 3000.
So all is great on a local machine. But, when I deploy, where should the server be hosted? Should I still connect to MongoDB from the user's local machine? Should I assume that the user will have port 4000 available on their local machine? Also, why do I even need to host the server? Wouldn't it be more efficient to simply request from the MongoDB database directly from the frontend rather than routing through a local server connection?
One last question: if I connect to MongoDB from the user's machine, at what point should I close that connection?
Thanks in advance for the help!
You can't simply connect to databases from frontend because it will expose your credentials and anybody can use your connection. To host your nodejs application, you will run it on a port on server machine(locally) and then use reverse proxy to route incoming requests to your server to the port where your application is running.