From cc9666e38fa08a111e2f2ff29ed4f4c7b99cc996 Mon Sep 17 00:00:00 2001 From: Tanner Linsley Date: Fri, 11 Sep 2026 17:24:12 -0600 Subject: [PATCH] docs(start): add tested image and font recipes --- docs/start/config.json | 4 + .../framework/react/guide/images-and-fonts.md | 150 ++++++++++++++++++ .../framework/react/migrate-from-next-js.md | 2 +- examples/react/start-images-fonts/.gitignore | 7 + examples/react/start-images-fonts/README.md | 37 +++++ .../start-images-fonts/artwork/coast.svg | 12 ++ .../react/start-images-fonts/package.json | 32 ++++ .../start-images-fonts/playwright.config.ts | 11 ++ .../start-images-fonts/scripts/images.mjs | 14 ++ .../start-images-fonts/src/routeTree.gen.ts | 68 ++++++++ .../react/start-images-fonts/src/router.tsx | 5 + .../start-images-fonts/src/routes/__root.tsx | 42 +++++ .../start-images-fonts/src/routes/index.tsx | 35 ++++ .../react/start-images-fonts/src/styles.css | 38 +++++ .../start-images-fonts/tests/assets.spec.ts | 77 +++++++++ .../react/start-images-fonts/tsconfig.json | 21 +++ .../react/start-images-fonts/vite.config.ts | 8 + pnpm-lock.yaml | 54 +++++++ 18 files changed, 616 insertions(+), 1 deletion(-) create mode 100644 docs/start/framework/react/guide/images-and-fonts.md create mode 100644 examples/react/start-images-fonts/.gitignore create mode 100644 examples/react/start-images-fonts/README.md create mode 100644 examples/react/start-images-fonts/artwork/coast.svg create mode 100644 examples/react/start-images-fonts/package.json create mode 100644 examples/react/start-images-fonts/playwright.config.ts create mode 100644 examples/react/start-images-fonts/scripts/images.mjs create mode 100644 examples/react/start-images-fonts/src/routeTree.gen.ts create mode 100644 examples/react/start-images-fonts/src/router.tsx create mode 100644 examples/react/start-images-fonts/src/routes/__root.tsx create mode 100644 examples/react/start-images-fonts/src/routes/index.tsx create mode 100644 examples/react/start-images-fonts/src/styles.css create mode 100644 examples/react/start-images-fonts/tests/assets.spec.ts create mode 100644 examples/react/start-images-fonts/tsconfig.json create mode 100644 examples/react/start-images-fonts/vite.config.ts diff --git a/docs/start/config.json b/docs/start/config.json index 8fa644fc1c..4dce741a28 100644 --- a/docs/start/config.json +++ b/docs/start/config.json @@ -378,6 +378,10 @@ "label": "Rendering Markdown", "to": "framework/react/guide/rendering-markdown" }, + { + "label": "Images and Fonts", + "to": "framework/react/guide/images-and-fonts" + }, { "label": "SEO", "to": "framework/react/guide/seo" diff --git a/docs/start/framework/react/guide/images-and-fonts.md b/docs/start/framework/react/guide/images-and-fonts.md new file mode 100644 index 0000000000..a8f2ceaec4 --- /dev/null +++ b/docs/start/framework/react/guide/images-and-fonts.md @@ -0,0 +1,150 @@ +--- +id: images-and-fonts +title: Images and Fonts +description: Build responsive images and self-hosted fonts in TanStack Start, with a tested example, image-service configuration, loading priority, and remote-image limits. +--- + +TanStack Start renders standard image elements and CSS font declarations. It does not include the `next/image` transformation server or `next/font` build API. Choose where image files are resized and where font files are served, then verify the production output. + +The [runnable image and font example](https://github.com/TanStack/router/tree/main/examples/react/start-images-fonts) uses build-time image resizing and a self-hosted variable font. It runs locally without service credentials and tests responsive selection, reserved image space, fallback text, and font requests. + +## Choose where images are transformed + +| Source | Transformation | Delivery | +| -------------------------------------- | ------------------------------------------------------- | --------------------------------------- | +| A small set of checked-in assets | Generate sizes during the build | Your application's static assets | +| A CMS or changing public image library | An image service generates sizes | Its CDN or your configured image domain | +| Private uploads | A service with authorization and a defined cache policy | Authorized delivery URLs | + +An image component controls markup such as `srcset`, `sizes`, dimensions, and loading. An image service fetches, resizes, encodes, and caches the bytes. A component such as [Unpic](https://unpic.pics/img/react/) can generate URLs for supported services, but installing it does not turn an arbitrary origin into a transformation server. Start's [CDN Asset URLs](./cdn-asset-urls) feature rewrites asset locations; it does not resize images either. + +## Generate local image sizes + +The example uses [Sharp](https://sharp.pixelplumbing.com/api-resize/) as a development dependency. Its build script creates 480, 960, and 1600 pixel WebP versions before Vite starts. Sharp stays out of the browser and request handler. The build environment must support its native binaries. + +```js +import sharp from 'sharp' + +for (const width of [480, 960, 1600]) { + await sharp('artwork/coast.svg') + .resize({ width, withoutEnlargement: true }) + .webp({ quality: 80 }) + .toFile(`src/assets/coast-${width}.webp`) +} +``` + +Create the output directory first, as the example's script does. Keep source assets outside `public` when visitors do not need the originals. The example sets Vite's `build.assetsInlineLimit` to `0` so small candidates remain separate files instead of data URLs embedded in the markup. Import generated files so Vite can fingerprint them: + +```tsx +import small from '../assets/coast-480.webp' +import medium from '../assets/coast-960.webp' +import large from '../assets/coast-1600.webp' +;A lighthouse above layered blue cliffs and a quiet bay +``` + +This markup matches a container capped at 960 CSS pixels with 16 pixels of space on either side of smaller screens: + +```css +main { + width: min(960px, calc(100% - 32px)); + margin-inline: auto; +} +img { + display: block; + width: 100%; + height: auto; +} +``` + +Change `sizes` when the actual layout changes. It describes the rendered width, not the original file width. A wrong value can make a small card download a large hero image. The width descriptors must match the files' actual pixel widths, including when a smaller original prevents enlargement. The example's source is 1600 pixels wide, so all three descriptors are accurate. + +The `width` and `height` attributes reserve the aspect ratio before bytes arrive. Keep that ratio consistent across candidates. Use `` when mobile needs a different crop or you want format-specific sources, and provide an `` fallback. Meaningful images need useful alt text; decorative images should use `alt=""`. + +Do not lazy-load the main above-the-fold image. Give high fetch priority only to an image likely to be the page's largest visible content. For offscreen images, use `loading="lazy"` and ordinary priority. Avoid adding a second preload unless a network trace shows late discovery; an incorrect preload can fetch an unused candidate. See the [HTML image reference](https://developer.mozilla.org/en-US/docs/Web/HTML/Reference/Elements/img). + +## Configure an image service + +For images that change after a deployment, use a transformation service instead of rebuilding every variant. For example, Cloudflare's URL interface uses a configured zone, transformation options, and a source path: + +```text +https://images.example.com/cdn-cgi/image/width=960,quality=80,format=auto/photos/coast.jpg +``` + +This is a configuration example, not a working public endpoint. Enable transformations for your zone, configure allowed source origins, and make the original reachable to that service. The `/cdn-cgi/image/` prefix alone does not enable processing on a plain local server or another host. Follow the provider's [URL configuration](https://developers.cloudflare.com/images/optimization/features/) and [source-origin controls](https://developers.cloudflare.com/images/optimization/transformations/sources/) for your deployment. + +Generate a finite set of widths for `srcSet`, using the same dimensions and `sizes` rules as the local example. If you use Unpic, select a supported provider and pass that provider's source URL and layout configuration. Inspect the URLs it emits and fetch them directly. Check the returned image dimensions and content type; successful HTML rendering does not prove that resizing happened. + +Before exposing remote transformations: + +- Restrict source hosts and paths at the service or server boundary. A browser-side allowlist does not protect a publicly callable endpoint. Check redirect behavior too: Cloudflare documents that its source-origin check applies to the initial URL, while redirects are followed. +- Bound dimensions, decoded pixels, input bytes, processing time, output formats, and animation frames. Avoid unbounded transformations controlled by arbitrary query strings. +- Enforce authorization before serving private originals or derived images. Do not put private images into a shared public cache or expose signing secrets in client code. +- Define cache keys, expiry, and invalidation for changed originals. Include transformation parameters in the cache identity. Use versioned source URLs when replacing content. +- Verify unsupported formats, missing sources, timeouts, and rejected origins. Review the service's limits and costs before expanding the allowed variants. + +The local example has no remote fetch endpoint. It therefore does not demonstrate a secure general-purpose image proxy or validate a provider account's settings. + +## Self-host a font + +Install a licensed font package such as [Fontsource Inter](https://fontsource.org/fonts/inter/install), or keep licensed WOFF2 files in your source tree. The example pins `@fontsource-variable/inter` and references only its normal Latin variable file: + +```css +@font-face { + font-family: 'Inter'; + src: url('@fontsource-variable/inter/files/inter-latin-wght-normal.woff2') + format('woff2'); + font-style: normal; + font-weight: 100 900; + font-display: optional; +} +body { + font-family: 'Inter', system-ui, sans-serif; +} +``` + +One variable file covers the weights used by this page. Import only the subsets and styles your content needs. A Latin-only face does not cover every language, and normal text does not provide a true italic face. Preserve the font's license when redistributing files. + +`font-display: optional` allows a slow visit to retain the fallback font instead of swapping later. Use `swap` when displaying the chosen typeface after download matters more, and measure the resulting layout shift. `swap` alone does not make fallback metrics match. If you add `size-adjust`, ascent, descent, or line-gap overrides, derive them from the actual font pair and test wrapping at your supported sizes. See [font-display](https://developer.mozilla.org/en-US/docs/Web/CSS/Reference/At-rules/@font-face/font-display). + +For a critical font used immediately, preload the same URL that CSS requests. In the root route: + +```tsx +import fontUrl from '@fontsource-variable/inter/files/inter-latin-wght-normal.woff2?url' +import cssUrl from '../styles.css?url' + +head: () => ({ + links: [ + { rel: 'stylesheet', href: cssUrl }, + { + rel: 'preload', + href: fontUrl, + as: 'font', + type: 'font/woff2', + crossOrigin: 'anonymous', + }, + ], +}) +``` + +Render `` in the document head, as shown in the example. Preloading every weight or a font used only on another route competes with more useful requests. Keep the preload's URL and cross-origin mode aligned with the font request to avoid duplicate downloads. Fonts served from a separate origin also need that server's CORS configuration. + +## Verify the production build + +Run the example's browser tests in both development and production modes. Then repeat the checks on your deployed hostname: + +1. Inspect initial HTML for image sources, dimensions, `sizes`, and the intended font preload. +2. Use fresh browser contexts for narrow and wide viewports at different device pixel ratios. Inspect `currentSrc` and the downloaded file's actual dimensions. A browser can reuse a larger cached candidate, so shrinking an already-loaded tab is not a clean selection test. +3. Block image and font requests. The image should retain its space and the text should remain usable. Check layout shift separately under throttling. +4. Inspect the network waterfall for duplicate fonts, unexpected third-party requests, oversized images, and failures. Confirm content types and cache headers on the final host. +5. Check your real photographs and content. The example's small illustration verifies the pipeline, not a universal image-quality setting or a field performance score. + +For migrating application behavior beyond these assets, see [Migrate from Next.js](../migrate-from-next-js). For deployment checks, use the [Production Checklist](./production-checklist). diff --git a/docs/start/framework/react/migrate-from-next-js.md b/docs/start/framework/react/migrate-from-next-js.md index 5739846a95..429c8e896b 100644 --- a/docs/start/framework/react/migrate-from-next-js.md +++ b/docs/start/framework/react/migrate-from-next-js.md @@ -166,7 +166,7 @@ Start does not automatically provide the Next.js image optimizer. Preserve image Replace `next/font` with self-hosted font files, a package such as Fontsource, or another chosen font delivery method. CSS `@font-face` does not require Tailwind. Preserve font weights and subsets, set an appropriate `font-display`, and check layout shift and network requests. Copy public assets and update imports only after confirming their resulting URLs. -The reference uses text and the browser's default font. It does not claim to verify your image transformations or font loading. +The migration reference uses text and the browser's default font. Use the separate [Images and Fonts guide](./guide/images-and-fonts) and its runnable example to verify responsive image output and local font loading. ## Rebuild caching and deployment behavior diff --git a/examples/react/start-images-fonts/.gitignore b/examples/react/start-images-fonts/.gitignore new file mode 100644 index 0000000000..2c5040e2a2 --- /dev/null +++ b/examples/react/start-images-fonts/.gitignore @@ -0,0 +1,7 @@ +node_modules +.output +.tanstack +dist +test-results +playwright-report +src/assets/ diff --git a/examples/react/start-images-fonts/README.md b/examples/react/start-images-fonts/README.md new file mode 100644 index 0000000000..2b06f5828e --- /dev/null +++ b/examples/react/start-images-fonts/README.md @@ -0,0 +1,37 @@ +# Responsive images and local fonts + +This Start example generates three WebP sizes before Vite runs, serves them through `srcSet`, and loads one Latin variable font from the same origin. It needs no image-service account or runtime transformation server. + +From the repository root, install with `pnpm install`, then: + +```sh +cd examples/react/start-images-fonts +pnpm dev +``` + +Open http://127.0.0.1:3130. For a production build: + +```sh +pnpm build +PORT=3130 pnpm start +``` + +The Nitro output needs a compatible Node host. Deploy the complete output, including public assets. Sharp runs only during development setup and builds; it is not imported into the application. A build machine needs Sharp's supported native binaries. The Vite configuration disables asset inlining so even the smallest candidate is a separately cached file. Vite fingerprints generated images and the font, so changing their content changes their public URLs. Configure your host's cache policy for those fingerprinted assets. + +`artwork/coast.svg` is an original illustration included under this repository's MIT license. It is a small deterministic input for the image pipeline, not a photographic compression benchmark. The Inter font package carries its own SIL Open Font License. Preserve that license when redistributing its font files. + +The image is capped at 960 CSS pixels. `sizes` describes that layout, and the browser chooses among 480, 960, and 1600 pixel files. The largest source caps high-density output at 1600 pixels deliberately. Increase the source size and candidates if your design requires more detail. The eager hero has explicit dimensions and high fetch priority. Images below the fold should normally use `loading="lazy"` and omit high priority. + +The font uses `font-display: optional`, which lets a slow first visit keep the system font instead of swapping late. This trades consistent first-visit typography for stability. The exact same font URL is used in CSS and the preload. Only normal Latin text is covered; add licensed subsets and italic faces if your content needs them. + +## Verify + +```sh +pnpm test:e2e +pnpm build +IMAGES_PRODUCTION=1 pnpm test:e2e +``` + +Tests check mobile and desktop source selection at two pixel densities, reserved image space when downloads fail, visible fallback text, and one same-origin font request. Use fresh browser contexts when testing responsive selection, because a browser may reuse a larger image already in its cache. These checks are local examples, not field Core Web Vitals measurements. + +See the [Images and Fonts guide](https://tanstack.com/start/latest/docs/framework/react/guide/images-and-fonts) for image-service configuration and migration choices. diff --git a/examples/react/start-images-fonts/artwork/coast.svg b/examples/react/start-images-fonts/artwork/coast.svg new file mode 100644 index 0000000000..f4442c2e6d --- /dev/null +++ b/examples/react/start-images-fonts/artwork/coast.svg @@ -0,0 +1,12 @@ + + + + + + + + + + + + diff --git a/examples/react/start-images-fonts/package.json b/examples/react/start-images-fonts/package.json new file mode 100644 index 0000000000..6e43f84450 --- /dev/null +++ b/examples/react/start-images-fonts/package.json @@ -0,0 +1,32 @@ +{ + "name": "tanstack-start-example-images-fonts", + "private": true, + "sideEffects": false, + "type": "module", + "scripts": { + "assets": "node scripts/images.mjs", + "dev": "pnpm assets && vite dev --host 127.0.0.1 --port 3130", + "build": "pnpm assets && vite build && tsc --noEmit", + "start": "node .output/server/index.mjs", + "test:e2e": "playwright test" + }, + "dependencies": { + "@tanstack/react-router": "^1.170.35", + "@tanstack/react-start": "^1.168.52", + "react": "^19.0.0", + "react-dom": "^19.0.0", + "@fontsource-variable/inter": "5.3.0" + }, + "devDependencies": { + "@types/node": "^22.5.4", + "@types/react": "^19.0.8", + "@types/react-dom": "^19.0.3", + "@vitejs/plugin-react": "^6.0.1", + "nitro": "^3.0.260311-beta", + "@typescript/native": "npm:typescript@^7.0.2", + "typescript": "npm:@typescript/typescript6@^6.0.2", + "vite": "^8.0.14", + "sharp": "0.35.4", + "@playwright/test": "^1.61.0" + } +} diff --git a/examples/react/start-images-fonts/playwright.config.ts b/examples/react/start-images-fonts/playwright.config.ts new file mode 100644 index 0000000000..e1c8490c44 --- /dev/null +++ b/examples/react/start-images-fonts/playwright.config.ts @@ -0,0 +1,11 @@ +import { defineConfig } from '@playwright/test' +const production = process.env.IMAGES_PRODUCTION === '1' +export default defineConfig({ + testDir: './tests', + use: { baseURL: 'http://127.0.0.1:3130', browserName: 'chromium' }, + webServer: { + command: production ? 'PORT=3130 pnpm start' : 'pnpm dev', + url: 'http://127.0.0.1:3130', + timeout: 120_000, + }, +}) diff --git a/examples/react/start-images-fonts/scripts/images.mjs b/examples/react/start-images-fonts/scripts/images.mjs new file mode 100644 index 0000000000..8d474cd924 --- /dev/null +++ b/examples/react/start-images-fonts/scripts/images.mjs @@ -0,0 +1,14 @@ +import { mkdir } from 'node:fs/promises' +import sharp from 'sharp' +import { fileURLToPath } from 'node:url' +await mkdir(new URL('../src/assets/', import.meta.url), { recursive: true }) +for (const width of [480, 960, 1600]) { + await sharp(fileURLToPath(new URL('../artwork/coast.svg', import.meta.url))) + .resize({ width, withoutEnlargement: true }) + .webp({ quality: 80 }) + .toFile( + fileURLToPath( + new URL(`../src/assets/coast-${width}.webp`, import.meta.url), + ), + ) +} diff --git a/examples/react/start-images-fonts/src/routeTree.gen.ts b/examples/react/start-images-fonts/src/routeTree.gen.ts new file mode 100644 index 0000000000..dceedffdc1 --- /dev/null +++ b/examples/react/start-images-fonts/src/routeTree.gen.ts @@ -0,0 +1,68 @@ +/* eslint-disable */ + +// @ts-nocheck + +// noinspection JSUnusedGlobalSymbols + +// This file was automatically generated by TanStack Router. +// You should NOT make any changes in this file as it will be overwritten. +// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. + +import { Route as rootRouteImport } from './routes/__root' +import { Route as IndexRouteImport } from './routes/index' + +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => rootRouteImport, +} as any) + +export interface FileRoutesByFullPath { + '/': typeof IndexRoute +} +export interface FileRoutesByTo { + '/': typeof IndexRoute +} +export interface FileRoutesById { + __root__: typeof rootRouteImport + '/': typeof IndexRoute +} +export interface FileRouteTypes { + fileRoutesByFullPath: FileRoutesByFullPath + fullPaths: '/' + fileRoutesByTo: FileRoutesByTo + to: '/' + id: '__root__' | '/' + fileRoutesById: FileRoutesById +} +export interface RootRouteChildren { + IndexRoute: typeof IndexRoute +} + +declare module '@tanstack/react-router' { + interface FileRoutesByPath { + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport + parentRoute: typeof rootRouteImport + } + } +} + +const rootRouteChildren: RootRouteChildren = { + IndexRoute: IndexRoute, +} +export const routeTree = rootRouteImport + ._addFileChildren(rootRouteChildren) + ._addFileTypes() + +import type { getRouter } from './router.tsx' +import type { createStart } from '@tanstack/react-start' +declare module '@tanstack/react-start' { + interface Register { + ssr: true + router: Awaited> + } +} diff --git a/examples/react/start-images-fonts/src/router.tsx b/examples/react/start-images-fonts/src/router.tsx new file mode 100644 index 0000000000..bb899b1fdf --- /dev/null +++ b/examples/react/start-images-fonts/src/router.tsx @@ -0,0 +1,5 @@ +import { createRouter } from '@tanstack/react-router' +import { routeTree } from './routeTree.gen' +export function getRouter() { + return createRouter({ routeTree }) +} diff --git a/examples/react/start-images-fonts/src/routes/__root.tsx b/examples/react/start-images-fonts/src/routes/__root.tsx new file mode 100644 index 0000000000..d0cbff0d33 --- /dev/null +++ b/examples/react/start-images-fonts/src/routes/__root.tsx @@ -0,0 +1,42 @@ +import { + createRootRoute, + HeadContent, + Outlet, + Scripts, +} from '@tanstack/react-router' +import type { ReactNode } from 'react' +import fontUrl from '@fontsource-variable/inter/files/inter-latin-wght-normal.woff2?url' +import cssUrl from '../styles.css?url' +export const Route = createRootRoute({ + head: () => ({ + meta: [ + { charSet: 'utf-8' }, + { name: 'viewport', content: 'width=device-width, initial-scale=1' }, + ], + links: [ + { rel: 'stylesheet', href: cssUrl }, + { + rel: 'preload', + href: fontUrl, + as: 'font', + type: 'font/woff2', + crossOrigin: 'anonymous', + }, + ], + }), + component: Outlet, + shellComponent: Document, +}) +function Document({ children }: { children: ReactNode }) { + return ( + + + + + + {children} + + + + ) +} diff --git a/examples/react/start-images-fonts/src/routes/index.tsx b/examples/react/start-images-fonts/src/routes/index.tsx new file mode 100644 index 0000000000..66ed25a5f0 --- /dev/null +++ b/examples/react/start-images-fonts/src/routes/index.tsx @@ -0,0 +1,35 @@ +import { createFileRoute } from '@tanstack/react-router' +import small from '../assets/coast-480.webp' +import medium from '../assets/coast-960.webp' +import large from '../assets/coast-1600.webp' +export const Route = createFileRoute('/')({ + head: () => ({ + meta: [ + { title: 'Coastal field notes' }, + { + name: 'description', + content: + 'An illustrated coast with responsive images and a self-hosted variable font.', + }, + ], + }), + component: Page, +}) +function Page() { + return ( +
+

Coastal field notes

+ A lighthouse above layered blue cliffs and a quiet bay +

The last light catches the headland before the tide turns.

+
+ ) +} diff --git a/examples/react/start-images-fonts/src/styles.css b/examples/react/start-images-fonts/src/styles.css new file mode 100644 index 0000000000..39d58551fd --- /dev/null +++ b/examples/react/start-images-fonts/src/styles.css @@ -0,0 +1,38 @@ +@font-face { + font-family: 'Inter'; + src: url('@fontsource-variable/inter/files/inter-latin-wght-normal.woff2') + format('woff2'); + font-style: normal; + font-weight: 100 900; + font-display: optional; +} +* { + box-sizing: border-box; +} +body { + margin: 0; + background: #f7f4ec; + color: #193347; + font-family: 'Inter', system-ui, sans-serif; +} +main { + width: min(960px, calc(100% - 32px)); + margin: 48px auto; +} +h1 { + font-size: clamp(2rem, 5vw, 3.5rem); + line-height: 1.1; + font-weight: 650; + letter-spacing: -0.04em; +} +img { + display: block; + width: 100%; + height: auto; + border-radius: 8px; +} +p { + font-size: 1.125rem; + line-height: 1.6; + max-width: 40rem; +} diff --git a/examples/react/start-images-fonts/tests/assets.spec.ts b/examples/react/start-images-fonts/tests/assets.spec.ts new file mode 100644 index 0000000000..0bdd5af170 --- /dev/null +++ b/examples/react/start-images-fonts/tests/assets.spec.ts @@ -0,0 +1,77 @@ +import { expect, test } from '@playwright/test' +import sharp from 'sharp' + +for (const [width, deviceScaleFactor, candidate] of [ + [390, 1, 480], + [390, 2, 960], + [1280, 1, 960], + [1280, 2, 1600], +]) { + test(`image at ${width}px and ${deviceScaleFactor}x`, async ({ browser }) => { + const context = await browser.newContext({ + viewport: { width, height: 900 }, + deviceScaleFactor, + }) + const page = await context.newPage() + const response = await page.goto('http://127.0.0.1:3130') + expect(response?.status()).toBe(200) + expect(await response!.text()).toMatch(/srcset=/i) + const image = page.getByRole('img') + await expect(image).toHaveJSProperty('complete', true) + const selected = await image.evaluate((element) => { + if (!(element instanceof HTMLImageElement)) { + throw new Error('Expected an image') + } + return element.currentSrc + }) + expect(selected).toContain(`coast-${candidate}`) + const downloaded = await page.request.get(selected) + expect(downloaded.ok()).toBe(true) + const metadata = await sharp(await downloaded.body()).metadata() + expect(metadata.width).toBe(candidate) + expect(metadata.height).toBe((candidate * 9) / 16) + const size = await image.boundingBox() + expect(size?.width).toBe(Math.min(960, width - 32)) + expect(size!.height / size!.width).toBeCloseTo(9 / 16, 2) + await context.close() + }) +} + +test('image dimensions survive failed downloads and fallback text stays visible', async ({ + page, +}) => { + await page.route('**/*.webp*', (route) => route.abort()) + await page.route('**/*.woff2*', (route) => route.abort()) + await page.goto('/') + await expect( + page.getByRole('heading', { name: 'Coastal field notes' }), + ).toBeVisible() + const size = await page.getByRole('img').boundingBox() + expect(size!.height / size!.width).toBeCloseTo(9 / 16, 2) +}) + +test('one same-origin font supplies the used weights', async ({ page }) => { + const fontResponses: string[] = [] + const externalRequests: string[] = [] + page.on('request', (request) => { + if (!request.url().startsWith('http://127.0.0.1:3130/')) { + externalRequests.push(request.url()) + } + }) + page.on('response', (response) => { + if (response.url().includes('.woff2')) { + fontResponses.push(response.url()) + } + }) + await page.goto('/') + await page.evaluate(() => document.fonts.ready) + expect( + await page.evaluate(() => document.fonts.check('650 24px Inter')), + ).toBe(true) + expect(fontResponses).toHaveLength(1) + expect(externalRequests).toEqual([]) + const preload = page.locator('link[as="font"]') + const href = await preload.getAttribute('href') + expect(new URL(href!, page.url()).href).toBe(fontResponses[0]) + await expect(preload).toHaveAttribute('crossorigin', 'anonymous') +}) diff --git a/examples/react/start-images-fonts/tsconfig.json b/examples/react/start-images-fonts/tsconfig.json new file mode 100644 index 0000000000..cc479423a1 --- /dev/null +++ b/examples/react/start-images-fonts/tsconfig.json @@ -0,0 +1,21 @@ +{ + "include": ["**/*.ts", "**/*.tsx", "**/*.d.ts"], + "compilerOptions": { + "strict": true, + "esModuleInterop": true, + "jsx": "react-jsx", + "module": "ESNext", + "moduleResolution": "Bundler", + "lib": ["DOM", "DOM.Iterable", "ES2024"], + "isolatedModules": true, + "resolveJsonModule": true, + "skipLibCheck": true, + "target": "ES2024", + "allowJs": true, + "forceConsistentCasingInFileNames": true, + "paths": { + "~/*": ["./src/*"] + }, + "noEmit": true + } +} diff --git a/examples/react/start-images-fonts/vite.config.ts b/examples/react/start-images-fonts/vite.config.ts new file mode 100644 index 0000000000..6a09769f5d --- /dev/null +++ b/examples/react/start-images-fonts/vite.config.ts @@ -0,0 +1,8 @@ +import { tanstackStart } from '@tanstack/react-start/plugin/vite' +import { defineConfig } from 'vite' +import viteReact from '@vitejs/plugin-react' +import { nitro } from 'nitro/vite' +export default defineConfig({ + build: { assetsInlineLimit: 0 }, + plugins: [tanstackStart(), viteReact(), nitro()], +}) diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 08b44bf2db..cf4dccd323 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -15628,6 +15628,55 @@ importers: specifier: ^8.0.14 version: 8.0.14(@types/node@25.0.9)(esbuild@0.28.2)(jiti@2.7.0)(sass@1.97.2)(terser@5.51.2)(tsx@4.20.3)(yaml@2.9.0) + examples/react/start-images-fonts: + dependencies: + '@fontsource-variable/inter': + specifier: 5.3.0 + version: 5.3.0 + '@tanstack/react-router': + specifier: workspace:* + version: link:../../../packages/react-router + '@tanstack/react-start': + specifier: workspace:* + version: link:../../../packages/react-start + react: + specifier: ^19.2.3 + version: 19.2.3 + react-dom: + specifier: ^19.2.3 + version: 19.2.3(react@19.2.3) + devDependencies: + '@playwright/test': + specifier: ^1.61.0 + version: 1.61.1 + '@types/node': + specifier: 25.0.9 + version: 25.0.9 + '@types/react': + specifier: ^19.2.8 + version: 19.2.9 + '@types/react-dom': + specifier: ^19.2.3 + version: 19.2.3(@types/react@19.2.9) + '@typescript/native': + specifier: npm:typescript@^7.0.2 + version: typescript@7.0.2 + '@vitejs/plugin-react': + specifier: ^6.0.1 + version: 6.0.1(@rolldown/plugin-babel@0.2.3(@babel/core@7.29.7(supports-color@10.2.2))(rolldown@1.0.2)(vite@8.0.14(@types/node@25.0.9)(esbuild@0.28.2)(jiti@2.7.0)(sass@1.97.2)(terser@5.51.2)(tsx@4.20.3)(yaml@2.9.0)))(babel-plugin-react-compiler@1.0.0)(vite@8.0.14(@types/node@25.0.9)(esbuild@0.28.2)(jiti@2.7.0)(sass@1.97.2)(terser@5.51.2)(tsx@4.20.3)(yaml@2.9.0)) + nitro: + specifier: ^3.0.260311-beta + version: 3.0.260311-beta(@electric-sql/pglite@0.3.2)(@emnapi/core@1.11.3)(@emnapi/runtime@1.11.3)(@libsql/client@0.15.15)(@netlify/blobs@10.1.0)(chokidar@5.0.0)(dotenv@17.4.2)(giget@2.0.0)(ioredis@5.11.1(supports-color@10.2.2))(jiti@2.7.0)(lru-cache@11.5.1)(miniflare@4.20260317.0)(mysql2@3.15.3)(rollup@4.63.1)(vite@8.0.14(@types/node@25.0.9)(esbuild@0.27.4)(jiti@2.7.0)(sass@1.97.2)(terser@5.37.0)(tsx@4.20.3)(yaml@2.9.0)) + sharp: + specifier: 0.35.4 + version: 0.35.4(@types/node@25.0.9) + typescript: + specifier: npm:@typescript/typescript6@^6.0.2 + version: '@typescript/typescript6@6.0.2' + vite: + specifier: ^8.0.14 + version: 8.0.14(@types/node@25.0.9)(esbuild@0.28.2)(jiti@2.7.0)(sass@1.97.2)(terser@5.51.2)(tsx@4.20.3)(yaml@2.9.0) + packages: '@adobe/css-tools@4.4.1': @@ -29787,6 +29836,9 @@ packages: cpu: [x64] os: [win32] + '@fontsource-variable/inter@5.3.0': + resolution: {integrity: sha512-OupL48va4JNofb97w6NYeF9S7W/kHNKM0Er8Dem5nqi4jeOLrVJDoE8tZEpnMJmtkvNbB1EIPPwHcdkF6b1oUA==} + snapshots: '@adobe/css-tools@4.4.1': {} @@ -46057,3 +46109,5 @@ snapshots: - mysql2 - sqlite3 - uploadthing + + '@fontsource-variable/inter@5.3.0': {}