Last active
July 9, 2024 23:05
-
-
Save wobsoriano/074bab8690f597b18417366be1ecb44c to your computer and use it in GitHub Desktop.
Server Side to Client Store Rehydration in SvelteKit (kinda)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { user } from './store.js' | |
user.set(window__SK__USER__) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** @type {import('@sveltejs/kit').Handle} */ | |
export async function handle({ event, resolve }) { | |
const user = await getUserInformation(event.cookies.get('sessionid')); | |
return resolve(event, { | |
transformPageChunk({ html }) { | |
const scriptContent = `<script>window.__SK_USER__ = ${JSON.stringify(user)}</script>`; | |
return insertScriptBeforeHeadEnd(html, scriptContent) | |
} | |
}) | |
} | |
function insertScriptBeforeHeadEnd(htmlString, scriptContent) { | |
const headEndIndex = htmlString.toLowerCase().indexOf('</head>'); | |
return htmlString.slice(0, headEndIndex) + scriptContent + htmlString.slice(headEndIndex); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment