-
-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathentry.server.tsx
80 lines (68 loc) · 2.14 KB
/
entry.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
import type { EntryContext } from "@remix-run/cloudflare";
import { RemixServer } from "@remix-run/react";
import { createInstance } from "i18next";
import { renderToString } from "react-dom/server";
import { I18nextProvider, initReactI18next } from "react-i18next";
import en from "~/locales/en";
import es from "~/locales/es";
import { i18n } from "~/services/i18n.server";
import { measure } from "./utils/measure";
export default function handleRequest(
request: Request,
statusCode: number,
headers: Headers,
context: EntryContext
) {
return measure("entry.server#handleRequest", async () => {
let instance = createInstance().use(initReactI18next);
let lng = await i18n.getLocale(request);
let ns = i18n.getRouteNamespaces(context);
await instance.init({
supportedLngs: ["es", "en"],
fallbackLng: "en",
react: { useSuspense: false },
lng,
ns,
resources: { en: { translation: en }, es: { translation: es } },
interpolation: { escapeValue: false },
});
let markup = renderToString(
<I18nextProvider i18n={instance}>
<RemixServer context={context} url={request.url} />
</I18nextProvider>
);
headers.set("Content-Type", "text/html");
prefetchAssets(context, headers);
return new Response("<!DOCTYPE html>" + markup, {
status: statusCode,
headers: headers,
});
});
}
function prefetchAssets(context: EntryContext, headers: Headers) {
let links = context.matches
.flatMap((match) => {
let route = context.routeModules[match.route.id];
if (route.links instanceof Function) return route.links();
return [];
})
.map((link) => {
if ("as" in link && "href" in link) {
return { href: link.href, as: link.as } as const;
}
if ("rel" in link && "href" in link) {
if (link.rel === "stylesheet")
return { href: link.href, as: "style" } as const;
}
return null;
})
.filter((link: any): link is { href: string; as: string } => {
return link && "href" in link;
})
.filter((item, index, list) => {
return index === list.findIndex((link) => link.href === item.href);
});
for (let link of links) {
headers.append("Link", `<${link.href}>; rel=preload; as=${link.as}`);
}
}