How can I host my API and web app on the same domain? How can I host my API and web app on the same domain? express express

How can I host my API and web app on the same domain?


Usually you don't expose such web applications directly to clients. Instead you use a proxy server, that forwards all incoming requests to the node or rails server.

nginx is a popular choice for that. The beginners guide even contains a very similar example to what you're trying to do.

You could achieve what you want with a config similar to this:

server {    location /api/ {        proxy_pass http://localhost:8000;    }    location / {        proxy_pass http://localhost:3000;    }}

This is assuming your API runs locally on port 8000 and your express app on port 3000. Also this is not a full configuration file - this needs to be loaded in or added to the http block. Start with the default config of your distro.

When there are multiple location entries nginx chooses the most specific one. You could even add further entries, e.g. to serve static content.


While Svens answer is completely correct for the question given. I'd prefer doing it at the DNS level so that I can change the server to a new location just in case my API or Web App experience heavy load. This helps us to run our APIs without affecting WebApp and vice-versa

DNS Structure

api.mysite.com => 9.9.9.9mysite.com = > 9.9.9.9

Since now you'd want both your WebApp and API to run on the same server, you can use nginx to forward requests appropriately.

server {    listen       80;    server_name api.mysite.com;    # ..    # Removed for simplicity    # ..    location / {        proxy_pass http://localhost:3000;    }}server {    listen      80;    server_name www.mysite.com;    # ..    # Removed for simplicity    # ..    location / {        proxy_pass http://localhost:8000;    }}

Any time in future if you are experiencing overwhelming traffic, you can just alter the DNS to point to a new server and you'd be good.