-
Notifications
You must be signed in to change notification settings - Fork 1
/
index-server.tsx
82 lines (75 loc) · 2.67 KB
/
index-server.tsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
import fetch from "cross-fetch"
import * as React from "react"
import { routes } from "~/routes"
import App from "../components/app/App"
import { languages, showDefaultLangInUrl } from "~/languages"
import { LangService, requestStaticPropsFromRoute, Router } from "@cher-ami/router"
import { GlobalDataContext } from "~/store/GlobalDataContext"
import { loadEnv } from "vite"
import { TScriptsObj } from "../../prerender/helpers/ManifestParser"
import { CherScripts } from "~/server/helpers/CherScripts"
import { RawScript } from "~/server/helpers/RawScript"
import { ViteDevScripts } from "~/server/helpers/ViteDevScripts"
import { ReactElement } from "react"
import { preventSlashes } from "~/server/helpers/preventSlashes"
// ----------------------------------------------------------------------------- PREPARE
/**
* Server render
* @param url
* @param isPrerender
* @param scripts
*/
// prettier-ignore
export async function render(
url: string,
scripts: TScriptsObj,
isPrerender = false
): Promise<ReactElement> {
// prepare base & URL
const base = process.env.VITE_APP_BASE || loadEnv("", process.cwd(), "").VITE_APP_BASE
url = preventSlashes(`${isPrerender ? base : ""}${url}`)
// Init lang service
const langService = new LangService({
staticLocation: url,
showDefaultLangInUrl,
languages,
base,
})
// Request static props
const ssrStaticProps = await requestStaticPropsFromRoute({ url, base, routes, langService })
const meta = ssrStaticProps?.props?.meta
const globalData = { foo: "bar" }
return (
<html lang={langService.currentLang.key}>
<head>
<meta charSet="UTF-8" />
<meta httpEquiv="x-ua-compatible" content="IE=Edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1" />
<title>{meta?.title || "app"}</title>
<meta name="description" content={meta?.description} />
<link rel="canonical" href={meta?.url || url} />
<ViteDevScripts />
<CherScripts scripts={scripts.css} />
<CherScripts scripts={scripts.woff2} />
</head>
<body>
<div id="root">
<Router
base={base}
routes={routes}
langService={langService}
staticLocation={url}
initialStaticProps={ssrStaticProps}
>
<GlobalDataContext.Provider value={globalData}>
<App />
</GlobalDataContext.Provider>
</Router>
</div>
<CherScripts scripts={scripts.js} />
<RawScript name={"__SSR_STATIC_PROPS__"} data={ssrStaticProps} />
<RawScript name={"__GLOBAL_DATA__"} data={globalData} />
</body>
</html>
)
}