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

seo.md

421 lines11.7 KB

1---
2id: seo
3title: SEO
4description: Configure SEO in TanStack Start with page metadata, canonical URLs, structured data, server rendering, sitemaps, and robots.txt.
5---
6​
7> [!NOTE]
8> Looking to optimize for AI assistants and LLMs? See the [Generative Engine Optimization (GEO) guide](./geo).
9​
10## What is SEO, really?
11​
12SEO (Search Engine Optimization) is often misunderstood as simply "showing up on Google" or a checkbox that a library can magically provide. In reality, SEO is a broad discipline focused on delivering valuable content that people need and making it easy for them to find.
13​
14**Technical SEO** is a subset of SEO that developers interact with most directly. It involves using tools and APIs that satisfy the technical requirements of search engines, crawlers, rankers, and even LLMs. When someone says a framework has "good SEO support," they typically mean it provides the tools to make this process straightforward.
15​
16TanStack Start provides comprehensive technical SEO capabilities, but you still need to put in the work to use them effectively.
17​
18## What TanStack Start Provides
19​
20TanStack Start gives you the building blocks for technical SEO:
21​
22- **Server-Side Rendering (SSR)** - Ensures crawlers receive fully rendered HTML
23- **Static Prerendering** - Pre-generates pages for optimal performance and crawlability
24- **Document Head Management** - Full control over meta tags, titles, and structured data
25- **Performance** - Fast load times through code-splitting, streaming, and optimized builds
26​
27## Document Head Management
28​
29The `head` property on routes is your primary tool for SEO. It allows you to set page titles, meta descriptions, Open Graph tags, and more.
30​
31### Basic Meta Tags
32​
33```tsx
34// src/routes/index.tsx
35import { createFileRoute } from '@tanstack/react-router'
36​
37export const Route = createFileRoute('/')({
38 head: () => ({
39 meta: [
40 { title: 'My App - Home' },
41 {
42 name: 'description',
43 content: 'Welcome to My App, a platform for...',
44 },
45 ],
46 }),
47 component: HomePage,
48})
49```
50​
51### Dynamic Meta Tags
52​
53Use loader data to generate dynamic meta tags for content pages:
54​
55```tsx
56// src/routes/posts/$postId.tsx
57import { createFileRoute } from '@tanstack/react-router'
58​
59export const Route = createFileRoute('/posts/$postId')({
60 loader: async ({ params }) => {
61 const post = await fetchPost(params.postId)
62 return { post }
63 },
64 head: ({ loaderData }) => ({
65 meta: [
66 { title: loaderData.post.title },
67 { name: 'description', content: loaderData.post.excerpt },
68 ],
69 }),
70 component: PostPage,
71})
72```
73​
74### Open Graph and Social Sharing
75​
76Open Graph tags control how your pages appear when shared on social media:
77​
78```tsx
79export const Route = createFileRoute('/posts/$postId')({
80 loader: async ({ params }) => {
81 const post = await fetchPost(params.postId)
82 return { post }
83 },
84 head: ({ loaderData }) => ({
85 meta: [
86 { title: loaderData.post.title },
87 { name: 'description', content: loaderData.post.excerpt },
88 // Open Graph
89 { property: 'og:title', content: loaderData.post.title },
90 { property: 'og:description', content: loaderData.post.excerpt },
91 { property: 'og:image', content: loaderData.post.coverImage },
92 { property: 'og:type', content: 'article' },
93 // Twitter Card
94 { name: 'twitter:card', content: 'summary_large_image' },
95 { name: 'twitter:title', content: loaderData.post.title },
96 { name: 'twitter:description', content: loaderData.post.excerpt },
97 { name: 'twitter:image', content: loaderData.post.coverImage },
98 ],
99 }),
100 component: PostPage,
101})
102```
103​
104### Canonical URLs
105​
106Canonical URLs help prevent duplicate content issues:
107​
108```tsx
109export const Route = createFileRoute('/posts/$postId')({
110 head: ({ params }) => ({
111 links: [
112 {
113 rel: 'canonical',
114 href: `https://myapp.com/posts/${params.postId}`,
115 },
116 ],
117 }),
118 component: PostPage,
119})
120```
121​
122## Structured Data (JSON-LD)
123​
124Structured data helps search engines understand your content and can enable rich results in search:
125​
126```tsx
127export const Route = createFileRoute('/posts/$postId')({
128 loader: async ({ params }) => {
129 const post = await fetchPost(params.postId)
130 return { post }
131 },
132 head: ({ loaderData }) => ({
133 meta: [{ title: loaderData.post.title }],
134 scripts: [
135 {
136 type: 'application/ld+json',
137 children: JSON.stringify({
138 '@context': 'https://schema.org',
139 '@type': 'Article',
140 headline: loaderData.post.title,
141 description: loaderData.post.excerpt,
142 image: loaderData.post.coverImage,
143 author: {
144 '@type': 'Person',
145 name: loaderData.post.author.name,
146 },
147 datePublished: loaderData.post.publishedAt,
148 }),
149 },
150 ],
151 }),
152 component: PostPage,
153})
154```
155​
156## Server-Side Rendering
157​
158SSR is enabled by default in TanStack Start. This ensures that search engine crawlers receive fully rendered HTML content, which is critical for SEO.
159​
160```tsx
161// SSR is automatic - your pages are rendered on the server
162export const Route = createFileRoute('/about')({
163 component: AboutPage,
164})
165```
166​
167For routes that don't need SSR, you can disable it selectively. However, be aware this may impact SEO for those pages:
168​
169```tsx
170// Only disable SSR for pages that don't need SEO
171export const Route = createFileRoute('/dashboard')({
172 ssr: false, // Dashboard doesn't need to be indexed
173 component: DashboardPage,
174})
175```
176​
177See the [Selective SSR guide](./selective-ssr) for more details.
178​
179## Static Prerendering
180​
181For content that doesn't change frequently, static prerendering generates HTML at build time for optimal performance:
182​
183<!-- ::start:tabs variant="bundler" -->
184​
185# Vite
186​
187```ts title="vite.config.ts"
188import { defineConfig } from 'vite'
189import { tanstackStart } from '@tanstack/react-start/plugin/vite'
190​
191export default defineConfig({
192 plugins: [
193 tanstackStart({
194 prerender: {
195 enabled: true,
196 crawlLinks: true,
197 },
198 }),
199 ],
200})
201```
202​
203# Rsbuild
204​
205```ts title="rsbuild.config.ts"
206import { defineConfig } from '@rsbuild/core'
207import { tanstackStart } from '@tanstack/react-start/plugin/rsbuild'
208​
209export default defineConfig({
210 plugins: [
211 tanstackStart({
212 prerender: {
213 enabled: true,
214 crawlLinks: true,
215 },
216 }),
217 ],
218})
219```
220​
221<!-- ::end:tabs -->
222​
223Prerendered pages load faster and are easily crawlable. See the [Static Prerendering guide](./static-prerendering) for configuration options.
224​
225## Sitemaps
226​
227### Built-in Sitemap Generation
228​
229TanStack Start can automatically generate a sitemap when you enable prerendering with link crawling:
230​
231<!-- ::start:tabs variant="bundler" -->
232​
233# Vite
234​
235```ts title="vite.config.ts"
236import { defineConfig } from 'vite'
237import { tanstackStart } from '@tanstack/react-start/plugin/vite'
238​
239export default defineConfig({
240 plugins: [
241 tanstackStart({
242 prerender: {
243 enabled: true,
244 crawlLinks: true, // Discovers all linkable pages
245 },
246 sitemap: {
247 enabled: true,
248 host: 'https://myapp.com',
249 },
250 }),
251 ],
252})
253```
254​
255# Rsbuild
256​
257```ts title="rsbuild.config.ts"
258import { defineConfig } from '@rsbuild/core'
259import { tanstackStart } from '@tanstack/react-start/plugin/rsbuild'
260​
261export default defineConfig({
262 plugins: [
263 tanstackStart({
264 prerender: {
265 enabled: true,
266 crawlLinks: true, // Discovers all linkable pages
267 },
268 sitemap: {
269 enabled: true,
270 host: 'https://myapp.com',
271 },
272 }),
273 ],
274})
275```
276​
277<!-- ::end:tabs -->
278​
279The sitemap is generated at build time by crawling all discoverable pages from your routes. This is the recommended approach for static or mostly-static sites.
280​
281### Static Sitemap
282​
283For simple sites, you can also place a static `sitemap.xml` file in your `public` directory:
284​
285```xml
286<!-- public/sitemap.xml -->
287<?xml version="1.0" encoding="UTF-8"?>
288<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
289 <url>
290 <loc>https://myapp.com/</loc>
291 <changefreq>daily</changefreq>
292 <priority>1.0</priority>
293 </url>
294 <url>
295 <loc>https://myapp.com/about</loc>
296 <changefreq>monthly</changefreq>
297 </url>
298</urlset>
299```
300​
301This approach works well when your site structure is known and doesn't change often.
302​
303### Dynamic Sitemap
304​
305For sites with dynamic content that can't be discovered at build time, you can create a dynamic sitemap using a [server route](./server-routes). Consider caching this at your CDN for performance:
306​
307```ts
308// src/routes/sitemap[.]xml.ts
309import { createFileRoute } from '@tanstack/react-router'
310​
311export const Route = createFileRoute('/sitemap.xml')({
312 server: {
313 handlers: {
314 GET: async () => {
315 const posts = await fetchAllPosts()
316​
317 const sitemap = `<?xml version="1.0" encoding="UTF-8"?>
318<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
319 <url>
320 <loc>https://myapp.com/</loc>
321 <changefreq>daily</changefreq>
322 <priority>1.0</priority>
323 </url>
324 ${posts
325 .map(
326 (post) => `
327 <url>
328 <loc>https://myapp.com/posts/${post.id}</loc>
329 <lastmod>${post.updatedAt}</lastmod>
330 <changefreq>weekly</changefreq>
331 </url>`,
332 )
333 .join('')}
334</urlset>`
335​
336 return new Response(sitemap, {
337 headers: {
338 'Content-Type': 'application/xml',
339 },
340 })
341 },
342 },
343 },
344})
345```
346​
347## robots.txt
348​
349### Static robots.txt
350​
351The simplest approach is to place a static `robots.txt` file in your `public` directory:
352​
353```txt
354// public/robots.txt
355User-agent: *
356Allow: /
357​
358Sitemap: https://myapp.com/sitemap.xml
359```
360​
361This file will be served automatically at `/robots.txt`. This is the most common approach for most sites.
362​
363### Dynamic robots.txt
364​
365For more complex scenarios (e.g., different rules per environment), you can create a robots.txt file using a [server route](./server-routes):
366​
367```ts
368// src/routes/robots[.]txt.ts
369import { createFileRoute } from '@tanstack/react-router'
370​
371export const Route = createFileRoute('/robots.txt')({
372 server: {
373 handlers: {
374 GET: async () => {
375 const robots = `User-agent: *
376Allow: /
377​
378Sitemap: https://myapp.com/sitemap.xml`
379​
380 return new Response(robots, {
381 headers: {
382 'Content-Type': 'text/plain',
383 },
384 })
385 },
386 },
387 },
388})
389```
390​
391## Best Practices
392​
393### Performance Matters
394​
395Page speed is a ranking factor. TanStack Start helps with:
396​
397- **Automatic code-splitting** - Only load the JavaScript needed for each page
398- **Streaming SSR** - Start sending HTML to the browser immediately
399- **Preloading** - Prefetch routes before users navigate to them
400​
401### Content is King
402​
403Technical SEO is just one piece of the puzzle. The most important factors are:
404​
405- **Quality content** - Create content that provides value to users
406- **Clear site structure** - Organize your routes logically
407- **Descriptive URLs** - Use meaningful path segments (`/posts/my-great-article` vs `/posts/123`)
408- **Internal linking** - Help users and crawlers discover your content
409​
410### Test Your Implementation
411​
412Use these tools to verify your SEO implementation:
413​
414- [Google Search Console](https://search.google.com/search-console) - Monitor indexing and search performance
415- [Google Rich Results Test](https://search.google.com/test/rich-results) - Validate structured data
416- [Open Graph Debugger](https://developers.facebook.com/tools/debug/) - Preview social sharing cards
417- Browser DevTools - Inspect rendered HTML and meta tags
418​
419### Track Your Rankings
420​
421To monitor your SEO performance over time, we recommend [Nozzle.io](https://nozzle.io?utm_source=tanstack). Nozzle provides enterprise-grade rank tracking that lets you monitor unlimited keywords, track SERP features, and analyze your visibility against competitors. Unlike traditional rank trackers, Nozzle stores the entire SERP for every query, giving you complete data to understand how your pages perform in search results.