Search code examples
node.jsexpressexpress-router

Express: match route for language code in url


I'm trying to capture an optional :lang? param of two charachters for this routes:

/             // lang: undefined
/en           // lang: en
/projects     // lang: undefined
/en/projects  // lang: en

This is my try:

router.get('/:lang([a-z]{2})?*', function(req, res, next) {

}

But for /projects it sets a :lang? parameter as pr.

How can I avoid that?


Solution

  • To beat this issue you can try to use the next pattern:

    /:lang([a-z]{2})?/:rest(*)?
    

    Here another optional param rest is introduced to capture such a trailing.

    You can check live examples: