1- import { useContext } from "preact/hooks" ;
21import renderToString from "preact-render-to-string" ;
32import type { ComponentType } from "preact" ;
43import type { Context , RouteModule } from "@impalajs/core" ;
5- import { HeadContext } from "./head-context" ;
4+ import { HeadContext , HeadManager } from "./head-context" ;
65
7- function HeadContent ( ) {
8- const headProvider = useContext ( HeadContext ) ;
9- return < > { ...headProvider . getHead ( ) } </ > ;
6+ function HeadContent ( { headManager } : { headManager : HeadManager } ) {
7+ return < > { ...headManager . getHead ( ) } </ > ;
108}
119
1210export async function render (
@@ -16,13 +14,21 @@ export async function render(
1614) {
1715 const { default : Page } = await mod ( ) ;
1816
19- const body = renderToString ( < Page { ...context } /> ) ;
17+ // We create a new head manager for each request to avoid sharing state across routes
18+ const headManager = new HeadManager ( ) ;
19+
20+ const body = renderToString (
21+ < HeadContext . Provider value = { headManager } >
22+ < Page { ...context } />
23+ </ HeadContext . Provider >
24+ ) ;
2025
2126 const modules = bootstrapModules ?. map (
2227 ( m ) => `<script type="module" src="${ m } "></script>`
2328 ) ;
2429
25- const headContent = renderToString ( < HeadContent /> ) ;
30+ // We then pass the head manager instance that is specific to this request to SSR
31+ const headContent = renderToString ( < HeadContent headManager = { headManager } /> ) ;
2632
2733 return {
2834 body,
0 commit comments