Created
January 20, 2023 20:44
-
-
Save BoDonkey/9c7211d6f43922e6a57ba62c84040c76 to your computer and use it in GitHub Desktop.
Middleware for redirecting based on locale
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module.exports = { | |
... | |
middleware(self, options) { | |
return { | |
checkLanguage(req, res, next) { | |
// if you are only doing this for the homepage, check that is the page being requested | |
// possibly using req.originalUrl or the url property | |
// https://v3.docs.apostrophecms.org/reference/module-api/module-overview.html#middleware-self | |
// make sure | |
// if not a page you need to redirect just return next() | |
let redirectLanguage = ''; | |
// get the browser languages | |
const language = req.headers['accept-language']; | |
// the browser languages are a word salad of country codes and | |
// preference indications | |
// parse out the preferred language, but you might want to use the `locale` package | |
// and (I think) locale.default | |
const preferredLanguage = <the value you parsed out>; | |
// store the value you got back | |
if (sessionStorage.getItem('preferredLanguage') === null) { | |
sessionStorage.setItem('preferredLanguage', preferredLanguage); | |
redirectLanguage = preferredLanguage; | |
} else { | |
redirectLanguage = sessionStorage.getItem('preferredLanguage'); | |
} | |
// add logic to figure out what page needs to be delivered set to correctUrl | |
// then test to see if a redirect is needed and set notCorrectPage to true | |
if (notCorrectPage) { | |
// you might want to think about an alert asking the person if they want a redirect | |
// instead of just redirecting | |
return res.send(correctUrl); | |
} | |
return next(); | |
} | |
}; | |
}, | |
... | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment