Search code examples
ruby-on-railsapiexpressserverhosting

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


I have a Rails API and a web app(using express), completely separate and independent from each other. What I want to know is, do I have to deploy them separately? If I do, how can I make it so that my api is in mysite.com/api and the web app in mysite.com/

I've seen many projects that do it that way, even have the api and the app in separate repos.


Solution

  • 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.