Skip to content

Instantly share code, notes, and snippets.

@focusaurus
Last active June 14, 2022 00:06
Show Gist options
  • Save focusaurus/5779340 to your computer and use it in GitHub Desktop.
Save focusaurus/5779340 to your computer and use it in GitHub Desktop.
Example of how a main express app can mount sub-applications on a mount point with app.use('/mount-point', subapp); If you GET /, you'll see the main_app's '/' response. If you GET /ep_app, you'll see the ep_app's '/' response.
const express = require("express");
const router = express.Router();
router.get('/', function (req, res) {
res.send("This is the '/' route in ep_app");
});
module.exports = router;
#!/usr/bin/env node
const express = require("express");
const http = require("http");
const mainRouter = express.Router();
const epRouter = require("./ep_app");
const server = express();
mainRouter.get('/', function (req, res) {
res.send("This is the '/' route in main_app");
});
server.use('/ep_app', epRouter);
server.use('/', mainRouter);
http.createServer(server).listen(3000);
@omfriyad
Copy link

I was looking for a perfect example of subapp and you're the savior! thank you!

@woodardj
Copy link

Are there negative (memory?) implications of building apps like this v. using a Router?

@coolaj86
Copy link

This should use a Router() app, not an express() server.

The difference is that certain security parameters (such as trust proxy) and other global state will not propagate properly if a new server is created.

Also, this should use http as the server for a similar reason - the express server conflicts with global state of the http server.

app.js:

'use strict';

var express = require("express");
var app = express.Router();

app.get('/', function (req, res) {
  res.json({ message: "This is the '/' route in ep_app" });
});

module.exports = app;

server.js:

#!/usr/bin/env node
'use strict';

var http = require('http');
var express = require("express");
var server = express();
var app = express.Router();
var epApp = require("./app.js");

app.get('/', function (req, res) {
  res.send("This is the '/' route in main_app");
});

server.use('/ep_app', epApp);
server.use('/', app);

http.createServer(server).listen(3000);

Why do so many people skip these steps and try to squish everything together? Documentation code golf.

@focusaurus
Copy link
Author

@coolaj86 I updated the gist to incorporate your tips. Thanks! Check back in another 9 years for further tweaks LOL.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment