76

I want to be able to host multiple NodeJS apps under the same domain, without using sub-domains (like google.com/reader instead of images.google.com). The problem is that I'm always typing the first part of the url e.g. "/reader" in Express/NodeJS.

How can I set up an Express app so that the base URL is something.com/myapp?

So instead of:

app.get("/myapp", function (req, res) {
   // can be accessed from something.com/myapp
});

I can do:

// Some set-up
app.base = "/myapp"

app.get("/", function (req, res) {
   // can still be accessed from something.com/myapp
});

I'd also like to configure Connect's staticProvider to behave the same way (right now it defaults to serving static files to something.com/js or something.com/css instead of something.com/myapp/js)

Chenmunka
  • 685
  • 4
  • 21
  • 25
David Tang
  • 92,262
  • 30
  • 167
  • 149

7 Answers7

154

The express router can handle this since 4.0

http://expressjs.com/en/api.html#router

http://bulkan-evcimen.com/using_express_router_instead_of_express_namespace.html

var express = require('express');
var app = express();
var router = express.Router();

// simple logger for this router's requests
// all requests to this router will first hit this middleware
router.use(function(req, res, next) {
  console.log('%s %s %s', req.method, req.url, req.path);
  next();
});

// this will only be invoked if the path ends in /bar
router.use('/bar', function(req, res, next) {
  // ... maybe some additional /bar logging ...
  next();
});

// always invoked
router.use(function(req, res, next) {
  res.send('Hello World');
});

app.use('/foo', router);

app.listen(3000);

Previous answer (before express 4.0) :

The express-namespace module (dead now) used to do the trick :

https://github.com/visionmedia/express-namespace

require('express-namespace');

app.namespace('/myapp', function() {
        app.get('/', function (req, res) {
           // can be accessed from something.com/myapp
        });
});
Remi Mélisson
  • 2,724
  • 2
  • 21
  • 13
  • 24
    Note to people from Google: this is the correct answer even though it is not marked. It's usually best to avoid monkey-patching a well-maintained library if at all possible. – Jonathan Dumaine Nov 26 '12 at 06:36
  • 4
    further note - project seems to be dead https://github.com/expressjs/express-namespace/issues/44 use the router in express 4 http://bulkan-evcimen.com/using_express_router_instead_of_express_namespace.html – CheapSteaks Aug 14 '14 at 18:39
  • Does this process eval thur redirects? e.g. resp.redirect('/') but really you intend to go to /myapp – Matthew Payne Jul 29 '15 at 18:55
22

At the moment this is not supported, and it's not easy to add it on your own.

The whole routing stuff is buried deep inside the server code, and as a bonus there's no exposure of the routes them selfs.

I dug through the source and also checked out the latest version of Express and the Connect middleware, but there's still no support for such functionality, you should open a issue either on Connect or Express itself.

Meanwhile...

Patch the thing yourself, here's a quick and easy way with only one line of code changed.

In ~/.local/lib/node/.npm/express/1.0.0/package/lib/express/servers.js, search for:

// Generate the route
this.routes[method](path, fn);

This should be around line 357, replace that with:

// Generate the route
this.routes[method](((self.settings.base || '') + path), fn);

Now just add the setting:

app.set('base', '/myapp');

This works fine with paths that are plain strings, for RegEx support you will have to hack around in the router middleware yourself, better file an issue in that case.

As far as the static provider goes, just add in /mypapp when setting it up.

Update

Made it work with RegExp too:

// replace
this.routes[method](baseRoute(self.settings.base || '', path), fn);

// helper
function baseRoute(base, path) {
    if (path instanceof RegExp) {
        var exp = RegExp(path).toString().slice(1, -1);
        return new RegExp(exp[0] === '^' ? '^' + base + exp.substring(1) : base + exp);

    } else {
        return (base || '') + path;
    }
}

I only tested this with a handful of expressions, so this isn't 100% tested but in theory it should work.

Update 2

Filed an issue with the patch:
https://github.com/visionmedia/express/issues/issue/478

Ivo Wetzel
  • 46,459
  • 16
  • 98
  • 112
  • Update: Fixed the broken patching of simple strings. – Ivo Wetzel Dec 07 '10 at 12:09
  • Thanks for the comprehensive answer. The solution for patching express works. However, passing a parameter to staticProvider only sets the root directory where the static files are found, not the url to which they are served. I'm guessing a similar patch can be made that removes the /myapp from the url. – David Tang Dec 07 '10 at 22:31
  • 2
    Overwriting a third party library is not wise since every time you update to a new version you also need to re-add your code to it. – Intervalia Dec 07 '17 at 17:32
13

Just to update the thread, now with Express.js v4 you can do it without using express-namespace:

var express = require('express'),
    forumRouter = express.Router(),
    threadRouter = express.Router(),
    app = express();

forumRouter.get('/:id)', function(req, res){
  res.send('GET forum ' + req.params.id);
});

forumRouter.get('/:id/edit', function(req, res){
  res.send('GET forum ' + req.params.id + ' edit page');
});


forumRouter.delete('/:id', function(req, res){
  res.send('DELETE forum ' + req.params.id);
});

app.use('/forum', forumRouter);

threadRouter.get('/:id/thread/:tid', function(req, res){
  res.send('GET forum ' + req.params.id + ' thread ' + req.params.tid);
});

forumRouter.use('/', threadRouter);

app.listen(app.get("port") || 3000);

Cheers!

danilodeveloper
  • 3,840
  • 2
  • 36
  • 56
7

I was able to achieve this using a combination of express-namespace for the routes and a fix from the below google group discussion for the static assets. This snippet will treat a request to /foo/javascripts/jquery.js like a request to /javascripts/jquery.js:

app.use('/foo', express.static(__dirname + '/public'));

Source: https://groups.google.com/forum/#!msg/express-js/xlP6_DX6he0/6OTY4hwfV-0J

Ben Zittlau
  • 2,345
  • 1
  • 21
  • 30
5

I know this is a very old question but Express has changed a lot since most these answers were posted so I thought I'd share my approach.

You can, of course, use Routers with Express 4 to group together related functionality behind a particular path. This is well documented and has already been covered by other answers.

However, it is also possible to mount an entire application at a particular path. As an example, let's assume our application (the one we want to host at /myapp) looks like this, in a file called myapp.js:

var express = require('express'),
    path = require('path'),
    app = express();

app.use(express.static(path.join(__dirname, 'public')));

app.get('/hello', function(req, res) {
    res.send('Hello');
});

// Lots of other stuff here

exports.app = app;

In our main js file we could then mount this whole application at the path /myapp:

var express = require('express'),
    app = express(),
    myApp = require('./myapp').app;

app.use('/myapp', myApp);

app.listen(3000);

Note that we've created two applications here, one mounted on the other. The main application could have further sub-apps mounted at different paths as required.

The code in myapp.js is completely independent of where it was mounted. It's similar to the structure used by the express-generator in that regard.

Some documentation about sub-apps can be found here:

https://expressjs.com/en/4x/api.html#app.mountpath https://expressjs.com/en/4x/api.html#app.onmount

skirtle
  • 27,868
  • 4
  • 42
  • 57
  • elegant solution that can be used to modularize the different apps, still works in 2021, shame express is dead – Shaybc Nov 25 '21 at 17:49
3

There are also reliability issues. If reliability is important, a common solution is to use a front-end reverse HTTP proxy such as nginx or HAProxy. They both use single-thread evented architecture and are thus very scalable.

Then you can have different node processes for different subsites, and if one site fails (uncaught exception, memory leak, programmer error, whatever) the rest of sub-sites continue to work.

nponeccop
  • 13,527
  • 1
  • 44
  • 106
1

I was looking for this feature but for API routes, not for static files. What I did was that when I initialized the router, I added the mount path. So my configuration looks like this

//Default configuration
app.configure(function(){
    app.use(express.compress());
    app.use(express.logger('dev'));
    app.set('json spaces',0);
    app.use(express.limit('2mb'));
    app.use(express.bodyParser());

    app.use('/api', app.router);        // <---

    app.use(function(err, req, res, callback){
        res.json(err.code, {});
    });
});

Notice the '/api' when calling the router

Diosney
  • 10,520
  • 15
  • 66
  • 111
Xerri
  • 4,916
  • 6
  • 45
  • 54
  • It worth to note that this solution works smoothly with express-resouce. I have several express subapps that provides an API below the prefix /api using this solution and a regular website at /. – Diosney Dec 14 '13 at 14:51
  • 1
    Just want to point out that: ```Error: 'app.router' is deprecated! Please see the 3.x to 4.x migration guide for details on how to update your app.``` – Alan Dong Nov 18 '18 at 08:42
  • app.router is deprecated – Shaybc Nov 25 '21 at 17:22