Reputation: 251
I built already many websites with Sapper and I love it, but now I'm using it to build a multilanguage website and that's a little harder.
I think I know how to deal with the strings' translation, but I'd like to be able to translate URLs too. For example /en/about should be /it/chi-siamo in italian and both should use /[lang]/about.svelte
I'm trying to override the URL on server.js but I can't make it work properly.
This is my server.js
import sirv from 'sirv';
import polka from 'polka';
import compression from 'compression';
import * as sapper from '@sapper/server';
import admin from './firebase/admin.js'
const { PORT, NODE_ENV } = process.env;
const dev = NODE_ENV === 'development';
const cv = customVars;
const server = polka(); // You can also use Express
if(dev) server.use(sirv('static', { dev: dev, etag: true, maxAge: 1000000, immutable: true }));
server
.use(
compression({ level: 9, threshold: 1000 }),
sapper.middleware()
)
// only listen when started in dev
server.listen(PORT, err => {
if (err) console.log('error', err);
});
export { sapper, cv, admin};
My question: How can I rewrite the URL so that when the user access on /it/chi-siamo it respondes with /[lang]/about.svelte?
Upvotes: 1
Views: 1439
Reputation: 29585
Unfortunately this isn't very straightforward at the moment without doing [lang]/[page]
. It's something we want to address in future though.
You could do this to mutate the request on the server, though it's a little messy:
const paths = {
it: {
'chi-siamo': 'about',
// others...
},
fr: {
// ...
},
// ...
};
server
.use(
compression({ threshold: 0 }),
(req, res, next) => {
const [, lang, ...parts] = req.url.split('/');
const path = (paths[lang] || {})[parts.join('/')];
if (path) {
// mutate the request object
req.url = req.path = req.originalUrl = `/${lang}/${path}`;
}
// let Sapper handle the mutated request
next();
},
sapper.middleware()
)
.listen(PORT, err => {
if (err) console.log('error', err);
});
But this won't affect client-side navigation, so if the user clicks a link to /it/chi-siamo
then the page won't be found, and Sapper will fall back to traditional server-side navigation, which isn't ideal.
Upvotes: 3