import type { SpeakConfig } from 'qwik-speak';
import { rewriteRoutes } from './speak-routes';
export const config: SpeakConfig = {
rewriteRoutes,
defaultLocale: { lang: 'en-US', currency: 'USD', timeZone: 'America/Los_Angeles' },
supportedLocales: [
{ lang: 'it-IT', currency: 'EUR', timeZone: 'Europe/Rome' },
{ lang: 'en-US', currency: 'USD', timeZone: 'America/Los_Angeles' }
],
// Translations available in the whole app
assets: [
'app'
],
// Translations with dynamic keys available in the whole app
runtimeAssets: [
'runtime'
]
};
Update plugin.ts in the root of the src/routes directory:
src/routes/plugin.ts
import type { RequestHandler } from "@builder.io/qwik-city";
import { extractFromUrl, setSpeakContext, validateLocale } from 'qwik-speak';
import { config } from '../speak-config';
/**
* This middleware function must only contain the logic to set the locale,
* because it is invoked on every request to the server.
* Avoid redirecting or throwing errors here, and prefer layouts or pages
*/
export const onRequest: RequestHandler = ({ locale, url }) => {
let lang: string | undefined = undefined;
const prefix = extractFromUrl(url);
if (prefix && validateLocale(prefix)) {
// Check supported locales
lang = config.supportedLocales.find(value => value.lang === prefix)?.lang;
} else {
lang = config.defaultLocale.lang;
}
// Set Speak context (optional: set the configuration on the server)
setSpeakContext(config);
// Set Qwik locale
locale(lang);
};
If you want to handle errors or redirects due to the locale, use layouts or pages. For example you could add in src/routes/layout.tsx:
export const onRequest: RequestHandler = ({ locale, error, redirect }) => {
// E.g. 404 error page
if (!locale()) throw error(404, 'Page not found for requested locale');
// E.g. Redirect
// if (!locale()) {
// const getPath = translatePath();
// throw redirect(302, getPath('/page', 'en-US')); // Let the server know the language to use
// }
};
Usage
Add index.tsx with some translation, providing optional default values for each translation: key@@[default value]:
i18n/en-US/app.json
i18n/it-IT/app.json
translations skipped due to dynamic keys: 1
extracted keys: 9
app asset for each language, initialized with the default values we provided.
translations skipped due to dynamic keys is runtime.${key}. During configuration, we provided in runtimeAssets a runtime file, which we can now create and populate with dynamic keys:
i18n/[lang]/runtime.json
{
"runtime": {
"dynamic": "I'm a dynamic value"
}
}
In SSG mode, you can only use always as prefix strategy
Prefix as needed
If in production you don't want the prefix for the default domains, change the prefix strategy to as-needed and invoke toPrefixAsNeeded for rewriteRoutes: