","inLanguage":"typescript"},{"@type":"CreativeWork","@id":"https://yourcheatsheets.org/cheatsheets/astro-intermediate#snippet-7","name":"View Transitions with custom animations","description":"Code example","text":"---\nimport { ViewTransitions } from 'astro:transitions';\n---\n\n \n\n\n\n\n
\n

Content with custom transition

\n
","inLanguage":"typescript"},{"@type":"CreativeWork","@id":"https://yourcheatsheets.org/cheatsheets/astro-intermediate#snippet-8","name":"Persistent state across View Transitions","description":"Code example","text":"---\nimport VideoPlayer from '../components/VideoPlayer.astro';\n---\n\n","inLanguage":"typescript"},{"@type":"CreativeWork","@id":"https://yourcheatsheets.org/cheatsheets/astro-intermediate#snippet-9","name":"API routes with database queries","description":"Code example","text":"// src/pages/api/users/[id].ts\nimport { db } from '../../../db';\n\nexport async function GET({ params, request }) {\n const { id } = params;\n const user = await db.user.findUnique({ where: { id } });\n \n if (!user) {\n return new Response(null, { status: 404 });\n }\n \n return new Response(JSON.stringify(user), {\n headers: { 'Content-Type': 'application/json' }\n });\n}\n\nexport async function PUT({ params, request }) {\n const { id } = params;\n const data = await request.json();\n const updated = await db.user.update({ where: { id }, data });\n \n return new Response(JSON.stringify(updated));\n}","inLanguage":"typescript"},{"@type":"CreativeWork","@id":"https://yourcheatsheets.org/cheatsheets/astro-intermediate#snippet-10","name":"Streaming SSR responses","description":"Code example","text":"// src/pages/feed.astro\n---\nexport const prerender = false;\n\nasync function* generateFeed() {\n for (let i = 1; i <= 10; i++) {\n const posts = await fetchPage(i);\n yield posts;\n await new Promise(r => setTimeout(r, 100));\n }\n}\n\nconst stream = generateFeed();\n---\n
\n {await Array.fromAsync(stream).then(pages => \n pages.flat().map(post =>
{post.title}
)\n )}\n
","inLanguage":"typescript"},{"@type":"CreativeWork","@id":"https://yourcheatsheets.org/cheatsheets/astro-intermediate#snippet-11","name":"Edge function deployment (Cloudflare)","description":"Code example","text":"// astro.config.mjs\nimport cloudflare from '@astrojs/cloudflare';\n\nexport default defineConfig({\n output: 'server',\n adapter: cloudflare({ mode: 'directory' }),\n vite: {\n ssr: {\n external: ['node:async_hooks']\n }\n }\n});","inLanguage":"typescript"},{"@type":"CreativeWork","@id":"https://yourcheatsheets.org/cheatsheets/astro-intermediate#snippet-12","name":"Build performance: concurrency optimization","description":"Code example","text":"// astro.config.mjs\nexport default defineConfig({\n build: {\n concurrency: 4, // Optimal for most systems\n inlineStylesheets: 'auto'\n },\n vite: {\n build: {\n rollupOptions: {\n output: {\n manualChunks: (id) => {\n if (id.includes('node_modules')) {\n return 'vendor';\n }\n }\n }\n }\n }\n }\n});","inLanguage":"typescript"},{"@type":"CreativeWork","@id":"https://yourcheatsheets.org/cheatsheets/astro-intermediate#snippet-13","name":"Memory optimization for large builds","description":"Code example","text":"// package.json\n{\n \"scripts\": {\n \"build\": \"NODE_OPTIONS='--max-old-space-size=8192' astro build\",\n \"build:fast\": \"NODE_OPTIONS='--max-old-space-size=8192' astro build --concurrency 4\"\n }\n}","inLanguage":"typescript"},{"@type":"CreativeWork","@id":"https://yourcheatsheets.org/cheatsheets/astro-intermediate#snippet-14","name":"Custom image loader for remote images","description":"Code example","text":"// astro.config.mjs\nexport default defineConfig({\n image: {\n service: {\n entrypoint: './src/imageService.ts',\n config: {\n baseUrl: 'https://cdn.example.com'\n }\n }\n }\n});\n\n// src/imageService.ts\nexport default {\n getURL(src, options) {\n return `${options.baseUrl}/${src}?w=${options.width}&q=${options.quality}`;\n }\n};","inLanguage":"typescript"},{"@type":"CreativeWork","@id":"https://yourcheatsheets.org/cheatsheets/astro-intermediate#snippet-15","name":"Dynamic OG images with Satori","description":"Code example","text":"// src/pages/og/[slug].png.ts\nimport satori from 'satori';\nimport { html } from 'satori-html';\nimport sharp from 'sharp';\n\nexport async function GET({ params }) {\n const svg = await satori(\n html`
\n

${params.slug}

\n
`,\n { width: 1200, height: 630 }\n );\n \n const png = await sharp(Buffer.from(svg)).png().toBuffer();\n \n return new Response(png, {\n headers: { 'Content-Type': 'image/png' }\n });\n}","inLanguage":"typescript"},{"@type":"CreativeWork","@id":"https://yourcheatsheets.org/cheatsheets/astro-intermediate#snippet-16","name":"Advanced error handling middleware","description":"Code example","text":"import { defineMiddleware } from 'astro:middleware';\n\nexport const onRequest = defineMiddleware(async (context, next) => {\n try {\n const response = await next();\n return response;\n } catch (error) {\n console.error('Request failed:', error);\n \n if (error.message.includes('database')) {\n return new Response('Database error', { status: 503 });\n }\n \n return new Response('Internal error', { status: 500 });\n }\n});","inLanguage":"typescript"},{"@type":"CreativeWork","@id":"https://yourcheatsheets.org/cheatsheets/astro-intermediate#snippet-17","name":"Rate limiting middleware","description":"Code example","text":"import { defineMiddleware } from 'astro:middleware';\nimport { RateLimiterMemory } from 'rate-limiter-flexible';\n\nconst limiter = new RateLimiterMemory({\n points: 100,\n duration: 60\n});\n\nexport const onRequest = defineMiddleware(async (context, next) => {\n const ip = context.clientAddress;\n \n try {\n await limiter.consume(ip);\n return next();\n } catch {\n return new Response('Rate limit exceeded', { \n status: 429,\n headers: { 'Retry-After': '60' }\n });\n }\n});","inLanguage":"typescript"},{"@type":"CreativeWork","@id":"https://yourcheatsheets.org/cheatsheets/astro-intermediate#snippet-18","name":"Internationalization with SSR","description":"Code example","text":"// astro.config.mjs\nexport default defineConfig({\n i18n: {\n defaultLocale: 'en',\n locales: ['en', 'fr', 'de', 'es'],\n routing: {\n prefixDefaultLocale: false\n }\n }\n});\n\n// src/middleware.ts\nexport const onRequest = defineMiddleware((context, next) => {\n const locale = context.preferredLocale || 'en';\n context.locals.locale = locale;\n return next();\n});","inLanguage":"typescript"},{"@type":"CreativeWork","@id":"https://yourcheatsheets.org/cheatsheets/astro-intermediate#snippet-19","name":"WebSocket integration for real-time features","description":"Code example","text":"// src/pages/api/ws.ts\nexport function GET() {\n // Upgrade HTTP to WebSocket\n const { socket, response } = Astro.upgradeWebSocket();\n \n socket.addEventListener('message', (event) => {\n const data = JSON.parse(event.data);\n // Broadcast to all clients\n socket.send(JSON.stringify({ type: 'update', data }));\n });\n \n return response;\n}","inLanguage":"typescript"},{"@type":"CreativeWork","@id":"https://yourcheatsheets.org/cheatsheets/astro-intermediate#snippet-20","name":"Partial prerendering for hybrid apps","description":"Code example","text":"// src/pages/products/[id].astro\nexport const prerender = false; // Dynamic\n\n// src/pages/about.astro\nexport const prerender = true; // Static\n\n// astro.config.mjs\nexport default defineConfig({\n output: 'hybrid', // Default to static, opt-in to SSR\n adapter: vercel({\n edgeMiddleware: true\n })\n});","inLanguage":"typescript"},{"@type":"CreativeWork","@id":"https://yourcheatsheets.org/cheatsheets/astro-intermediate#snippet-21","name":"Database connection pooling","description":"Code example","text":"// src/db.ts\nimport { Pool } from 'pg';\n\nlet pool: Pool;\n\nexport function getDb() {\n if (!pool) {\n pool = new Pool({\n host: import.meta.env.DB_HOST,\n database: import.meta.env.DB_NAME,\n max: 20,\n idleTimeoutMillis: 30000,\n connectionTimeoutMillis: 2000\n });\n }\n return pool;\n}\n\n// Use in API routes\nimport { getDb } from '../../../db';\nconst db = getDb();\nconst result = await db.query('SELECT * FROM users');","inLanguage":"typescript"},{"@type":"CreativeWork","@id":"https://yourcheatsheets.org/cheatsheets/astro-intermediate#snippet-22","name":"Smart asset optimization","description":"Code example","text":"// astro.config.mjs\nimport compress from 'astro-compress';\n\nexport default defineConfig({\n integrations: [\n compress({\n CSS: true,\n HTML: {\n removeAttributeQuotes: false,\n collapseWhitespace: true\n },\n Image: true,\n JavaScript: true,\n SVG: true\n })\n ],\n build: {\n assets: '_astro',\n inlineStylesheets: 'auto'\n }\n});","inLanguage":"typescript"},{"@type":"CreativeWork","@id":"https://yourcheatsheets.org/cheatsheets/astro-intermediate#snippet-23","name":"Advanced Content Collections with relationships","description":"Code example","text":"// src/content/config.ts\nimport { defineCollection, reference, z } from 'astro:content';\n\nconst authors = defineCollection({\n type: 'data',\n schema: z.object({\n name: z.string(),\n bio: z.string()\n })\n});\n\nconst posts = defineCollection({\n type: 'content',\n schema: z.object({\n title: z.string(),\n author: reference('authors'),\n relatedPosts: z.array(reference('posts')).optional()\n })\n});\n\nexport const collections = { authors, posts };","inLanguage":"typescript"},{"@type":"CreativeWork","@id":"https://yourcheatsheets.org/cheatsheets/astro-intermediate#snippet-24","name":"Custom dev toolbar app","description":"Code example","text":"// src/toolbar-app.ts\nimport type { DevToolbarApp } from 'astro';\n\nexport default {\n id: 'my-toolbar',\n name: 'Performance Monitor',\n icon: '...',\n init(canvas, eventTarget) {\n const button = document.createElement('button');\n button.textContent = 'Check Performance';\n button.onclick = async () => {\n const metrics = await measurePerformance();\n console.log('Metrics:', metrics);\n };\n canvas.appendChild(button);\n }\n} satisfies DevToolbarApp;\n\n// astro.config.mjs\nexport default defineConfig({\n devToolbar: {\n enabled: true\n }\n});","inLanguage":"typescript"}],"keywords":"Astro intermediate cheat sheet, Astro SSR configuration, Astro Content Layer API, Astro middleware tutorial, Astro performance optimization, Astro Server Islands, Astro View Transitions API, Astro SSR vs static, how to optimize Astro build times, Astro with databases, Astro edge deployment, Astro hybrid rendering, Astro, SSR, Performance, TypeScript, Edge Computing","about":[{"@type":"Thing","name":"Astro"},{"@type":"Thing","name":"SSR"},{"@type":"Thing","name":"Performance"},{"@type":"Thing","name":"TypeScript"},{"@type":"Thing","name":"Edge Computing"}]},{"@type":"ItemList","@id":"https://yourcheatsheets.org/cheatsheets/astro-intermediate#topics","name":"Core Concepts - Astro Intermediate Cheat Sheet DATA | SSR Configuration + Performance Optimization Guide","numberOfItems":5,"itemListElement":[{"@type":"ListItem","position":1,"name":"SSR Configuration: Hybrid Rendering","description":"output: 'hybrid' (default SSG) with per-route export const prerender = false for SSR, or output: 'server' (default SSR) with prerender = true for static. Adapters (node, vercel, netlify, cloudflare) handle platform deployment. See Astro SSR vs static examples below","url":"https://yourcheatsheets.org/cheatsheets/astro-intermediate#core-concepts"},{"@type":"ListItem","position":2,"name":"Content Layer API: Advanced Collections","description":"Astro 5.0+ Content Layer replaces frontmatter-only collections. Define loaders in defineCollection() to fetch from APIs, databases, or file systems. Supports remote data with build-time caching, reducing builds from 9000s to 2600s for 340k pages","url":"https://yourcheatsheets.org/cheatsheets/astro-intermediate#core-concepts"},{"@type":"ListItem","position":3,"name":"Astro middleware tutorial: Request Interception","description":"src/middleware.ts with defineMiddleware() intercepts all requests before rendering. Access context.locals to share data, modify responses, implement auth guards. Sequence() chains multiple middlewares in order","url":"https://yourcheatsheets.org/cheatsheets/astro-intermediate#core-concepts"},{"@type":"ListItem","position":4,"name":"Performance optimization: Server Islands","description":"server:defer directive delays non-critical SSR components (user reviews, recommendations) while serving static shell instantly. Reduces TTFB by 60-80%. Combines CDN static speed with dynamic server data in same route","url":"https://yourcheatsheets.org/cheatsheets/astro-intermediate#core-concepts"},{"@type":"ListItem","position":5,"name":"Astro View Transitions API: SPA-like Navigation","description":"Import ViewTransitions in layout for instant page transitions. transition:name links elements across pages, transition:animate customizes effects, transition:persist maintains state. Works without JavaScript fallback","url":"https://yourcheatsheets.org/cheatsheets/astro-intermediate#core-concepts"}]},{"@type":"TechArticle","@id":"https://yourcheatsheets.org/cheatsheets/astro-intermediate#article","headline":"Astro Intermediate Cheat Sheet DATA | SSR Configuration + Performance Optimization Guide","description":"Complete reference guide","image":[{"@type":"ImageObject","url":"https://yourcheatsheet.org/images/astro-intermediate-og","width":1200,"height":630},{"@type":"ImageObject","url":"https://yourcheatsheet.org/images/astro-intermediate-og","width":800,"height":800}],"author":{"@id":"https://yourcheatsheet.org/author/carla-stevens"},"publisher":{"@id":"https://yourcheatsheet.org/about"},"inLanguage":"en-US","isAccessibleForFree":true,"keywords":"Astro intermediate cheat sheet, Astro SSR configuration, Astro Content Layer API, Astro middleware tutorial, Astro performance optimization, Astro Server Islands, Astro View Transitions API, Astro SSR vs static, how to optimize Astro build times, Astro with databases, Astro edge deployment, Astro hybrid rendering, Astro, SSR, Performance, TypeScript, Edge Computing","speakable":{"@type":"SpeakableSpecification","cssSelector":["#top","#quick-start","#when-to-use","#core-concepts","#snippets","#master-commands","#production-examples","#production-fixes","#pitfalls","#troubleshooting","#elite-pro-hack","#workflows","#benchmark","#resources"]},"potentialAction":[{"@type":"ReadAction","target":{"@type":"EntryPoint","urlTemplate":"https://yourcheatsheets.org/cheatsheets/astro-intermediate"}},{"@type":"DownloadAction","name":"Download PDF","target":{"@type":"EntryPoint","urlTemplate":"https://yourcheatsheets.org/downloads/astro-intermediate.pdf"}}]},{"@type":"BreadcrumbList","@id":"https://yourcheatsheets.org/cheatsheets/astro-intermediate#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https://yourcheatsheet.org"},{"@type":"ListItem","position":2,"name":"Web-Development","item":"https://yourcheatsheet.org/categories/Web-Development"},{"@type":"ListItem","position":3,"name":"Astro Intermediate Cheat Sheet DATA | SSR Configuration + Performance Optimization Guide","item":"https://yourcheatsheets.org/cheatsheets/astro-intermediate"}]}]}

Quick Start with Astro Intermediate

Production-ready compilation flags and build commands

SSR Configuration: QUICK START (5s)

Copy → Paste → Live

npx astro add node
# Edit astro.config.mjs:
export default defineConfig({
  output: 'server',
  adapter: node({ mode: 'standalone' })
});
$
✓ SSR enabled with Node adapter
✓ Server running with dynamic routing
✓ Access Astro.clientAddress, Astro.request

Learn more in Astro middleware authentication section
⚡ 5s Setup

When to Use Astro Intermediate

Decision matrix per scegliere la tecnologia giusta

IDEAL USE CASES

  • Hybrid rendering applications mixing static pages with dynamic SSR routes for personalization and real-time data

  • Content-heavy sites with 10k+ pages requiring Content Layer API for optimized build performance (3-5x faster builds)

  • E-commerce platforms needing Server Islands for mixing static product catalogs with dynamic pricing and inventory

AVOID FOR

  • Simple static blogs without dynamic requirements - use basic SSG instead for simplicity

  • Real-time collaborative apps requiring constant WebSocket connections - consider Next.js or Remix

  • Projects where team lacks SSR/middleware experience - start with beginner Astro patterns first

Core Concepts of Astro Intermediate

Production-ready compilation flags and build commands

#1

SSR Configuration: Hybrid Rendering

output: 'hybrid' (default SSG) with per-route export const prerender = false for SSR, or output: 'server' (default SSR) with prerender = true for static. Adapters (node, vercel, netlify, cloudflare) handle platform deployment. See Astro SSR vs static examples below

✓ Solution
npx astro add node (or vercel/netlify). Updates astro.config.mjs automatically
+85% deployment flexibility
#2

Content Layer API: Advanced Collections

Astro 5.0+ Content Layer replaces frontmatter-only collections. Define loaders in defineCollection() to fetch from APIs, databases, or file systems. Supports remote data with build-time caching, reducing builds from 9000s to 2600s for 340k pages

✓ Solution
Migrate to loader pattern: defineCollection({ loader: async () => fetchData() })
+70% faster builds for large sites
#3

Astro middleware tutorial: Request Interception

src/middleware.ts with defineMiddleware() intercepts all requests before rendering. Access context.locals to share data, modify responses, implement auth guards. Sequence() chains multiple middlewares in order

+100% security implementation ease
Auth check in 2-5ms per request
#4

Performance optimization: Server Islands

server:defer directive delays non-critical SSR components (user reviews, recommendations) while serving static shell instantly. Reduces TTFB by 60-80%. Combines CDN static speed with dynamic server data in same route

✓ Solution
Requires output: 'server' or 'hybrid' with adapter installed
+75% faster Time to First Byte
#5

Astro View Transitions API: SPA-like Navigation

Import ViewTransitions in layout <head> for instant page transitions. transition:name links elements across pages, transition:animate customizes effects, transition:persist maintains state. Works without JavaScript fallback

+53% user session duration