Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

SSR: Better ServerEntry types #10412

Merged
merged 6 commits into from
Apr 4, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions .changesets/10412.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
- SSR: Better ServerEntry types (#10412) by @Tobbe

When enabling SSR the setup command will generate an `entry.server.tsx` file in
the user's app. This file exports a `ServerEntry` component that takes `css`
and ` meta` as props. The `meta` props used to be typed as `any`, making it
difficult to use with confidence. This PR makes the type be `TagDescriptor[]`
which is more correct.
4 changes: 3 additions & 1 deletion __fixtures__/test-project-rsa/web/src/entry.server.tsx
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
import type { TagDescriptor } from '@redwoodjs/web'

import App from './App'
import { Document } from './Document'

interface Props {
css: string[]
meta?: any[]
meta?: TagDescriptor[]
}

export const ServerEntry: React.FC<Props> = ({ css, meta }) => {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
import type { TagDescriptor } from '@redwoodjs/web'

import App from './App'
import { Document } from './Document'

interface Props {
css: string[]
meta?: any[]
meta?: TagDescriptor[]
}

export const ServerEntry: React.FC<Props> = ({ css, meta }) => {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
import type { TagDescriptor } from '@redwoodjs/web'

import App from './App'
import { Document } from './Document'

interface Props {
css: string[]
meta?: any[]
meta?: TagDescriptor[]
}

export const ServerEntry: React.FC<Props> = ({ css, meta }) => {
Expand Down
18 changes: 5 additions & 13 deletions packages/vite/src/middleware/register.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,21 +4,18 @@ import type { ViteDevServer } from 'vite'

import { getPaths } from '@redwoodjs/project-config'

import { makeFilePath } from '../utils'
import type { EntryServer } from '../types'
import { makeFilePath, ssrLoadEntryServer } from '../utils'

import type { MiddlewareRequest } from './MiddlewareRequest'
import { MiddlewareResponse } from './MiddlewareResponse'
import type {
Middleware,
MiddlewareClass,
MiddlewareInvokeOptions,
MiddlewareReg,
} from './types'

// Tuple of [mw, '*.{extension}']
export type MiddlewareReg = Array<
[Middleware | MiddlewareClass, string] | Middleware | MiddlewareClass
>

type GroupedMw = Record<string, Middleware[]>

const validateMw = (mw: MiddlewareClass | Middleware): Middleware => {
Expand Down Expand Up @@ -108,15 +105,10 @@ export const createMiddlewareRouter = async (
): Promise<Router.Instance<any>> => {
const rwPaths = getPaths()

const entryServerPath = rwPaths.web.entryServer

if (!entryServerPath) {
throw new Error('Entry server not found. Could not load middleware')
}
let entryServerImport: EntryServer

let entryServerImport: Record<'registerMiddleware', () => MiddlewareReg>
if (vite) {
entryServerImport = await vite.ssrLoadModule(entryServerPath)
entryServerImport = await ssrLoadEntryServer(vite)
} else {
// This imports from dist!
entryServerImport = await import(makeFilePath(rwPaths.web.distEntryServer))
Expand Down
5 changes: 5 additions & 0 deletions packages/vite/src/middleware/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,3 +18,8 @@ export type MiddlewareInvokeOptions = {
cssPaths?: Array<string>
params?: Record<string, unknown>
}

// Tuple of [mw, '*.{extension}']
export type MiddlewareReg = Array<
[Middleware | MiddlewareClass, string] | Middleware | MiddlewareClass
>
11 changes: 5 additions & 6 deletions packages/vite/src/streaming/createReactStreamingHandler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,8 @@ import type { TagDescriptor } from '@redwoodjs/web'
import { invoke } from '../middleware/invokeMiddleware.js'
import { MiddlewareResponse } from '../middleware/MiddlewareResponse.js'
import type { Middleware } from '../middleware/types.js'
import { makeFilePath } from '../utils.js'
import type { EntryServer } from '../types.js'
import { makeFilePath, ssrLoadEntryServer } from '../utils.js'

import { reactRenderToStreamResponse } from './streamHelpers.js'
import { loadAndRunRouteHooks } from './triggerRouteHooks.js'
Expand Down Expand Up @@ -43,8 +44,8 @@ export const createReactStreamingHandler = async (

const isProd = !viteDevServer
const middlewareRouter: Router.Instance<any> = await getMiddlewareRouter()
let entryServerImport: any
let fallbackDocumentImport: any
let entryServerImport: EntryServer
let fallbackDocumentImport: Record<string, any>

// Load the entries for prod only once, not in each handler invocation
// Dev is the opposite, we load it everytime to pick up changes
Expand Down Expand Up @@ -118,9 +119,7 @@ export const createReactStreamingHandler = async (
// Do this inside the handler for **dev-only**.
// This makes sure that changes to entry-server are picked up on refresh
if (!isProd) {
entryServerImport = await viteDevServer.ssrLoadModule(
rwPaths.web.entryServer as string, // already validated in dev server
)
entryServerImport = await ssrLoadEntryServer(viteDevServer)
fallbackDocumentImport = await viteDevServer.ssrLoadModule(
rwPaths.web.document,
)
Expand Down
8 changes: 4 additions & 4 deletions packages/vite/src/streaming/streamHelpers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,14 +19,15 @@ import {
} from '@redwoodjs/web/dist/components/ServerInject'

import type { MiddlewareResponse } from '../middleware/MiddlewareResponse.js'
import type { ServerEntryType } from '../types.js'

import { createBufferedTransformStream } from './transforms/bufferedTransform.js'
import { createTimeoutTransform } from './transforms/cancelTimeoutTransform.js'
import { createServerInjectionTransform } from './transforms/serverInjectionTransform.js'

interface RenderToStreamArgs {
ServerEntry: any
FallbackDocument: any
ServerEntry: ServerEntryType
FallbackDocument: React.FunctionComponent
currentPathName: string
metaTags: TagDescriptor[]
cssLinks: string[]
Expand Down Expand Up @@ -120,8 +121,7 @@ export async function reactRenderToStreamResponse(
{
value: injectToPage,
},
ServerEntry({
url: path,
React.createElement(ServerEntry, {
css: cssLinks,
meta: metaTags,
}),
Expand Down
20 changes: 20 additions & 0 deletions packages/vite/src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,27 @@
* **All** of these properties are used by the prod FE server
*/
import type { RWRouteManifestItem } from '@redwoodjs/internal'
import type { TagDescriptor } from '@redwoodjs/web'

import type { MiddlewareReg } from './middleware/types'

export type RWRouteManifest = Record<PathDefinition, RWRouteManifestItem>

type PathDefinition = string

export type ServerEntryType = React.FunctionComponent<{
css: string[]
meta: TagDescriptor[]
}>

export type EntryServer =
| {
registerMiddleware?: () => MiddlewareReg
ServerEntry: ServerEntryType
default: never
}
| {
registerMiddleware?: () => MiddlewareReg
ServerEntry: never
default: ServerEntryType
}
19 changes: 19 additions & 0 deletions packages/vite/src/utils.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
import type { ViteDevServer } from 'vite'

import { getPaths } from '@redwoodjs/project-config'

import type { EntryServer } from './types'

export function stripQueryStringAndHashFromPath(url: string) {
return url.split('?')[0].split('#')[0]
}
Expand All @@ -19,7 +23,22 @@ export function ensureProcessDirWeb(webDir: string = getPaths().web.base) {
process.chdir(webDir)
}
}

export function makeFilePath(path: string): string {
// Without this, absolute paths can't be imported on Windows
return 'file:///' + path
}

export async function ssrLoadEntryServer(viteDevServer: ViteDevServer) {
const rwPaths = getPaths()

if (!rwPaths.web.entryServer) {
throw new Error('entryServer not defined')
}

return viteDevServer.ssrLoadModule(
rwPaths.web.entryServer,
// Have to type cast here because ssrLoadModule just returns a generic
// Record<string, any> type
) as Promise<EntryServer>
}
2 changes: 2 additions & 0 deletions packages/web/ambient.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@
import type { NormalizedCacheObject } from '@apollo/client'
import type { HelmetServerState } from 'react-helmet-async'

import type { TagDescriptor } from '@redwoodjs/web'

declare global {
var __REDWOOD__PRERENDERING: boolean
var __REDWOOD__HELMET_CONTEXT: { helmet?: HelmetServerState }
Expand Down
Loading