Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to mount express.js sub-apps?

Tags:

node.js

I have several apps that I'm trying to merge into a single "suite": 2 apps are standalone, one is simply an auth layer (using everyauth for FB Connect). I want to set it up like so:

  • / - (home) list of the apps
  • /auth - login for any app
  • /app1 - requires login via /auth to access
  • /app2 - (same)

I've considered leaving app1 and app2 standalone, with the top layer being a proxy, but I think it would be hard to share an auth system between them. Virtualhosts (via Connect) might work, but I don't necessarily want a DNS'd subdomain for each one. So instead I'd like to primary app to be the auth layer, and the others "mounted" into that one, with basepath set on each app to a sub-path. (basepath is mentioned in the express Guide but not documented well.)

They all use MongoDB, the auth layer uses connect-mongodb for sessions, so I'm hoping they'll be able to share the whole auth/session layer between them.

In another thread, "How to share sessions in mounted express apps", Stephen writes,

I have a fairly complex express based web application that is split up into a few sub apps which are also express apps (using app.use()) ...

So how does one use app.use() to mount a sub-app? I was simply trying to use var subApp = require('./subapp/app.js'), with listen() running only in the sub-app when ! module.parent (so not as a sub-app)... but that seems to load all the sub-app's paths straight into the parent app. I've tried setting basepath using app.set('basepath', '/subapp/'), app.basepath = '/subapp/', etc, both in the sub-app itself and from the parent app, but it doesn't seem to have any effect.

Mounting apps like this makes express incredibly flexible, but it's not clear how to do it... any advice would be extremely welcome!! (And I'm happy to share lessons from my everyauth implementation if anyone is struggling with that.)

like image 896
thebuckst0p Avatar asked Dec 15 '11 01:12

thebuckst0p


People also ask

What is a sub app Express?

A sub-app can be defined as an instance of Express that may be used for handling the request to a route. This property is similar to the baseUrl property of the req object; the only difference is that req. baseUrl returns the matched URL path instead of the matched patterns.

Is Express js still used 2021?

Express is currently, and for many years, the de-facto library in the Node. js ecosystem. When you are looking for any tutorial to learn Node, Express is presented and taught to people.


1 Answers

app.use(uri, instanceOfExpressServer)

Just make sure you don't call .listen on it.

The alternative is to use require("cluster") and invoke all your apps in a single master so that they share the same port. Then just get the routing to "just work"

like image 137
Raynos Avatar answered Oct 04 '22 14:10

Raynos