Skip to content

Instantly share code, notes, and snippets.

@BoDonkey
Created January 20, 2023 20:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save BoDonkey/9c7211d6f43922e6a57ba62c84040c76 to your computer and use it in GitHub Desktop.
Save BoDonkey/9c7211d6f43922e6a57ba62c84040c76 to your computer and use it in GitHub Desktop.
Middleware for redirecting based on locale
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