Skip to content

Commit

Permalink
feat: Browser language detection
Browse files Browse the repository at this point in the history
Adds ability to automatically redirect new users to their favorite language based on browser's
accept-language

Closes nuxt-modules#37
  • Loading branch information
paulgv committed Mar 10, 2018
1 parent 728dcdd commit 755fa59
Show file tree
Hide file tree
Showing 3 changed files with 32 additions and 2 deletions.
4 changes: 3 additions & 1 deletion lib/module.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,9 @@ module.exports = function (moduleOptions) {
loadLanguagesAsync: false,
langDir: 'lang/',
langFiles: {},
ignorePaths: []
ignorePaths: [],
detectBrowserLanguage: false,
redirectCookieKey: 'redirected'
}
const options = merge(defaults, moduleOptions, this.options.i18n)

Expand Down
29 changes: 28 additions & 1 deletion lib/templates/i18n.routing.middleware.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import cookie from 'cookie';
import middleware from './middleware'

middleware['i18n'] = function ({ app, route, redirect, error, hotReload }) {
middleware['i18n'] = function ({ app, req, res, route, params, redirect, error, hotReload }) {
const locales = <%= JSON.stringify(options.locales) %>
const localeCodes = locales.map(l => l.code)
const defaultLocale = '<%= options.defaultLocale %>'
Expand All @@ -14,6 +15,32 @@ middleware['i18n'] = function ({ app, route, redirect, error, hotReload }) {
localeCodes.includes('<%= options.redirectRootToLocale %>')) {
redirect('/<%= options.redirectRootToLocale %>/')
}

// Handle browser language detection
if (<%= options.detectBrowserLanguage %> && req && route.name) {
const cookieKey = '<%= options.redirectCookieKey %>';
const cookies = cookie.parse(req.headers.cookie);
// Redirect only if cookie not set yet
if (!cookies[cookieKey]) {
const browserLocale = req.headers['accept-language'].split(',')[0].toLocaleLowerCase().substring(0, 2)
// Set cookie
if (res) {
const date = new Date();
const redirectCookie = cookie.serialize(cookieKey, 1, {
expires: new Date(date.setDate(date.getDate() + 365))
})
res.setHeader('Set-Cookie', redirectCookie);
}
// Redirect
if (browserLocale !== app.i18n.locale && localeCodes.indexOf(browserLocale) !== -1) {
app.i18n.locale = browserLocale
redirect(app.localePath(Object.assign({}, route , {
name: app.getRouteBaseName()
})));
}
}
}

// Get locale from params
let locale = defaultLocale
locales.forEach(l => {
Expand Down
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@
]
},
"dependencies": {
"cookie": "^0.3.1",
"vue-i18n": "^7.3.2",
"vue-i18n-extensions": "^0.1.0"
},
Expand Down

0 comments on commit 755fa59

Please sign in to comment.