Repository navigation
|
For example, such code works in SvelteKit 2: import { browser } from '$app/env'; // '$app/environment' in SvelteKit 2
import { getRequestEvent } from '$app/server';
type Language = 'en' | 'zh';
let current = $state<Language>();
export function getLanguage(): Language {
return current ?? getDefaultLanguage();
}
export function setLanguage(language: Language) {
current = language;
document.cookie = `improviser1999_language=${language}; max-age=34560000; path=/`;
}
function getDefaultLanguage(): Language {
if (browser) {
return resolveDefaultLanguageBrowser();
} else {
return resolveDefaultLanguageServer();
}
}
function resolveDefaultLanguageBrowser() {
console.log(navigator.languages); // resolve language from navigator
return 'en' as const;
}
function resolveDefaultLanguageServer() {
const { request, cookies } = getRequestEvent();
console.log({ request, cookies }); // resolve language from http request
return 'en' as const;
}But the build fails with How to do similar things in SvelteKit 3? |
Answered by
teemingc
Oct 3, 2026
Replies: 1 comment 2 replies
|
Refactor your browser and server logic into separate files. Then, import them through a subpath import, specifying a |
2 replies
Answer selected by
teemingc
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Refactor your browser and server logic into separate files. Then, import them through a subpath import, specifying a
browsercondition resolving to the client logic, and adefaultcondition resolving to the server logic. This means you simply importgetDefaultLanguagefrom, for example,#lib/language.tsand always resolve the correct browser/server variant depending on where it’s used, without relying on dead code elimination which Rolldown is unable to do correctly at present.