Subdomain middleware in loopback - is there a way to serve static files based on subdomain?

19 views
Skip to first unread message

Jackson Vaughan

unread,
Apr 16, 2018, 10:52:20 PM4/16/18
to LoopbackJS
Also have this posted in stackoverflow.

I've got two angular 2 client apps that I'd like to serve from my loopback backend. I've been able to serve them successfully from subdirectories (www.mysite.com/subdirectory), but I'm trying to serve them from subdomains (www.subdomain.mysite.com).

Loopback doesn't seem to have a built in way to handle subdomain routing through the middleware or anywhere else that I can see. So I'm trying to accomplish the routing by matching the hostname in a url-not-found-handler that is set for final in the middleware.json file as such:

  if (req.hostname.match(/subdomain1\./g)) {
    console.log('requesting subdomain1 site')
    res.sendFile(path.resolve() + '/dist/subdomain1/index.html')
  } else if (req.hostname.match(/subdomain2\./g)) {
    console.log('requesting subdomain2 site')
    res.sendFile(path.resolve() + '/dist/subdomain/index.html')
  } else {
    next();
  }

I've also got the static files in the middleware.json set up as such:

  "files": {
      "loopback#static": [
        {
          "name": "subdomain1",
          "params": "dist/subdomain1"
        },
        {
          "name": "subdomain2",
          "params": "dist/subdomain2"
        }
    ]
  }

This seems to work in that it properly matches and sends the correct index.html file. I know it's the right index.html by inspecting in the browser.

But for some reason the actual angular app that gets served ALWAYS is whatever is first in the loopback#static array. If I have subdomain2 first, that will be shown for both subdomain1.mysite.com as well as subdomain2.mysite.com.

How can I fix this issue and serve a different apps based on the subdomain?

Jackson Vaughan

unread,
Apr 17, 2018, 2:22:05 PM4/17/18
to LoopbackJS
For anyone else running into this issue, I figured out a solution that worked for me:


Would be awesome if this existed out of the box with loopback though!
Reply all
Reply to author
Forward
0 new messages