iuliu.net iuliu.net - 5 months ago 8x
Node.js Question

Match all routes but '/' in Express

I'm trying to create an authentication machanism for my app by checking cookies. So I added the

to match every request, check the cookie, and then go to the actual handler. But I need it to only match requests which have one or more characters after '/'. (I want to match
, but not

//Assuming a request for '/', this gets called first
router.all('*', function (request, response, next) {
//Stuff happening

//This gets called on next(), which I do not want
router.get('/', function (request, response) {
//Stuff happening

//However this I do want to be matched when requested and therefore called after router.all()
router.post('/about', function (request, response) {
//Stuff happening

According to the answers here you can use regex for path matching but then I don't really understand what
is. It might match everything, but it doesn't look like regex to me.

  1. Why does

  2. What argument do I need to suplly to
    to match
    but not


Simply put * last. The router checks in order of definition.


router.get('/' ...


router.all('*' ...

Just remember that / is still valid for *, so a next() call from / will trigger the catch all process.