Skip to content
Source
Sign inSign up
TanStack/router
Open History to see the last commit

entry-server.tsx

76 lines1.6 KB

1import * as React from 'react'
2import ReactDOMServer from 'react-dom/server'
3import { createMemoryHistory } from '@tanstack/react-router'
4import jsesc from 'jsesc'
5import { ServerResponse } from 'http'
6import { createRouter } from './router'
7import express from 'express'
8​
9// index.js
10import './fetch-polyfill'
11import { App } from '.'
12​
13async function getRouter(opts: { url: string }) {
14 const router = createRouter()
15​
16 const memoryHistory = createMemoryHistory({
17 initialEntries: [opts.url],
18 })
19​
20 router.update({
21 history: memoryHistory,
22 })
23​
24 await router.load()
25​
26 return router
28​
29export async function load(opts: { url: string }) {
30 const router = await getRouter(opts)
31​
32 const search = router.store.currentLocation.search as {
33 __data: { matchId: string }
34 }
35​
36 return router.store.currentMatches.find(
37 (d) => d.matchId === search.__data.matchId,
38 )?.store.routeLoaderData
40​
41export async function render(opts: {
42 url: string
43 head: string
44 req: express.Request
45 res: ServerResponse
46}) {
47 const router = await getRouter(opts)
48​
49 const routerState = router.dehydrate()
50​
51 const routerStateScript = `<script>
52 window.__TANSTACK_ROUTER_STATE__ = JSON.parse(${jsesc(
53 JSON.stringify(routerState),
54 {
55 isScriptContext: true,
56 wrap: true,
57 json: true,
58 },
59 )}
60 )
61 </script>`
62​
63 const context = {
64 head: `${opts.head}${routerStateScript}`,
65 }
66​
67 router.update({
68 context,
69 })
70​
71 const appHtml = ReactDOMServer.renderToString(<App router={router} />)
72​
73 opts.res.statusCode = 200
74 opts.res.setHeader('Content-Type', 'text/html')
75 opts.res.end(`<!DOCTYPE html>${appHtml}`)