Search code examples
reactjshostingnetlify

How to host multiple react apps from a single Netlify project?


Currently, I'm using a repository with at least 4 different apps. Its structure is something like this

root_folder/
  app1/
  app2/
  app3/
  app4/

Where each subdirectory is a react application. How do I use the Netlify Monorepo feature mentioned here? I want to use it in such a way that all the apps map under a single domain, eg: example.com, example.com/app1, example.com/app2 and so on.


Solution

  • There are two ways to do this.

    Multi-site way:

    Setup all the 4 repos as 4 different websites in the Netlify UI. You can specify the base directory for each and that should work fine. Then, you can create a 5th site which would make use of Netlify's Proxy rewrites: https://docs.netlify.com/routing/redirects/rewrites-proxies/

    In other words, the 5th website would be like the main website used to route to all other websites. Your netlify.toml in the 5th website would look something like:

    [[redirects]]
      from = "/path1/*"
      to = "https://site-from-app-1.netlify.app/"
      status = 200
    

    and more such rewrites for the rest of the apps.

    Single-site way:

    You'd have to make your build command like:

    cd ./app1/ && npm run build && cp -R ./build/ ../dist/app1/ && cd ../app2/ && npm run build && cp -R ./build/ ../dist/app2/ && cd ../app3/ ...
    

    Basically, you'd have to make a super long build command to cd into each directory, build the app, copy the built files into a single folder which you'd set as the publish folder in Netlify.