Static hosting has some limitation like no server side language redirection for e.g. search engines. Cloudflare Workers run on the edge and are very fast when switching from cold state to hot (allegedly 5ms wake up time). This is ideally for redirections based on HTTP headers, browser settings or geolocation.
This Cloudflare Worker script redirects all unlocalized paths to de
and en
languages expect:
'sw.js',
'sitemap.xml',
'robots.txt',
'icon.png',
'favicon-*.png',
'favicon.ico',
'_nuxt\\/.*',
'static\\/.*',
'de(\\/.*)?',
'en(\\/.*)?',
'404.html',
These exceptions are necessary as all incoming request have to go through the worker in Cloudflare. The reason for this is, that there are no look ahead patterns like execute this worker when there is no /de
in the path. Also common plugins like the next-i18next do it like mentioned above which can be seen in their code here on Github.
The second backslash (/
) in the definition paths is necessary because the code is transformed into a Regex in JS where slashes and backslashes have to be escaped.
- check if path is not a static or excluded one
- check if language was specified in the language cookie
- check if a supported language is given in the browser languages
- check if request comes from a german speaking country
- fallback to english as english is understood all over the globe
You have 3 possibilities to deploy this script to Cloudflare Workers:
- Copy the code from
index.js
and past it into the Cloudflare Workers Web Editor. - Install Cloudflare's CLI tool wrangler globally, login and deploy your script like here.
- Inject this project into a CI/CD pipeline, inject the wrangler ENV variables
CF_ACCOUNT_ID
,CF_ZONE_ID
andCF_API_TOKEN
respectively and run theyarn publish
command.
It is also possible to configure the associated domain via wrangler or the wrangler.toml
file like it's documented here. The domain can route all traffic coming from a NuxtJS app through this Worker. This means a URL trigger like https://domain.com/*
is suggestedd in the Cloudflare Workers tab on the domain settings page.