Search code examples
vue-router

How to setup multiple vue spa-apps on single server with nginx


I've encountered a task to run multiple vue spa apps with their own router on a single linux server.

In my case there is one backend that should serve two vue apps both on vite using nginx. Both apps using full router functionality such as query, path params, meta-data, named paths and etc.

So how can I do that?


Solution

  • First of all you should set base path in vite.config.js to path that you will use in nginx folder:

    export default defineConfig(({ mode }) => {
        return {
            base: "/first-app/",
        //Your other configuration...
    

    And set base route of application the same in your routes.ts:

    const routes: RouterOptions["routes"] = [
        {
            path: "/first-app",
            component: FirstAppLayout,
        //Your other routes...
    

    Same on the second app but with "second-app" instead.

    Remember to add router with history, I'm using createWebHistory in main.ts:

    import { createApp } from "vue";
    import { createRouter, createWebHistory } from "vue-router";
    
    const app = createApp(App);
    const history = createWebHistory();
    const router = createRouter({ history, routes });
    app.mount("#app");
    

    After that you must build your apps. I'm using vite but it is not so different on other builders. So I run this command:

    vite build
    

    You'll get your dist/ folder with built application (Of course you must build both of apps). Send both of built applications on your server. I'm sending them to /var/www/frontend folder in first-app/ for first app and second-app/ for second one, you can choose any other path but I consider to put them close to one another for future easier configuration.

    For multiple apps on same server you should tell nginx how to differ when it should be one app and when another. For that I suggest to use regex on location directive in your sites-available/default file like so:

    server {
      location ~ ^/first-app {
        root /var/www/frontend;
        try_files $uri $uri/ /first-app/index.html;
      }
    
      location ~ ^/second-app {
        root /var/www/frontend;
        try_files $uri $uri/ /second-app/index.html;
      }
    }
    

    After that run nginx and every time user goes to /first-app he'll get first app and to /second-app he'll get second app.