I am trying to set up routing for my multilingual website. My goal is to redirect the user based on his language (which is already detected).
This is my current unfinished code:
app.get('/(:lang)?', (req, res, next) => {
const urlLang = req.params.lang || 'en'; // English is default
const userLang = 'nl'; // Will be detected
if (urlLang !== userLang) {
// Wrong URL
res.redirect(userLang + req.url);
} else next();
});
In this example I try to subtract the requested language from the url (urlLang). If that language does not match the users language, then it should redirect to the proper URL.
A few examples of what I'm trying to achieve:
- User with language
enrequests/: No redirect - User with language
nlrequests/: Redirect to/nl - User with language
enrequests/foo/bar: No redirect - User with language
nlrequests/foo/bar: Redirect to/nl/foo/bar
My current code only works if the requested path is / or /:lang, but not for routes like /home or /nl/home. I don't see how this can be achieved with express. Any help will be much appreciated!
Please note I have already set up everything else, like language detection, translation logic, views, etc. I am only asking about the routing.
via Duncan Luk
No comments:
Post a Comment