Skip to content

Instantly share code, notes, and snippets.

@tilleps
Created January 13, 2020 06:30
Show Gist options
  • Save tilleps/4524f2471c298d084b19a154f588de93 to your computer and use it in GitHub Desktop.
Save tilleps/4524f2471c298d084b19a154f588de93 to your computer and use it in GitHub Desktop.
ExpressJS strict routing workaround
/*
Enforcing strict routing
https://github.com/expressjs/express/issues/2281
Use cases:
GET /strict -> noslash
GET /strict/ -> noslash (expect slash)
GET /strict// -> noslash (expect 404)
GET /strictslash -> noslash (expect 404)
GET /strictslash/ -> noslash
GET /strictslash// -> noslash (expect 404 or slash - not sure)
GET /strictslash/// -> noslash (expect 404)
//*/
const express = require("express");
const app = express();
app.set("strict routing", true);
const router = express.Router({ strict: true });
// Middleware to enforce strict URLs
router.use(function strict(req, res, next) {
if (req.app.get("strict routing")) {
req.url = req.originalUrl.substring(req.baseUrl.length);
}
next();
});
// Note: using .use() will not work:
// router.use("", function (req, res, next) {
router.all("", function (req, res, next) {
res.send("noslash");
});
// Note: using .use() will not work:
// router.use("", function (req, res, next) {
router.all("/", function(req, res) {
res.send("slash");
});
app.use("/strict", router);
app.use("/strictslash/", router);
app.listen(4000);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment