SSR & Adapters
เปิด server
หัวข้อที่มีชื่อว่า “เปิด server”on-demand rendering รัน component script ของคุณ ต่อ request คุณจึงอ่าน data ตอน request ได้ การจะรัน server code ต้องติดตั้ง adapter สำหรับแพลตฟอร์มปลายทางแล้วเพิ่มลง config:
import { defineConfig } from 'astro/config';import node from '@astrojs/node';
export default defineConfig({ adapter: node({ mode: 'standalone' }), // or cloudflare(), vercel(), netlify()});พอมี adapter route จะ render on demand ตรงที่ต้องการ (หรือเมื่อคุณตั้ง export const prerender = false บน route) ถ้าไม่มี ฟีเจอร์ on-demand จะ build ไม่ผ่านพร้อมข้อความ “an adapter is required”
sequenceDiagram participant B as Browser participant S as Astro server (adapter) participant C as Component script B->>S: GET /dashboard S->>C: run script with request context C->>C: read cookies, user, query params C-->>S: HTML + response settings S-->>B: Response (status, headers, body)
อ่าน request
หัวข้อที่มีชื่อว่า “อ่าน request”ภายใน on-demand page หรือ endpoint global Astro เปิดให้เข้าถึง request:
---export const prerender = false;
const url = Astro.url; // a URL objectconst q = url.searchParams.get('q'); // query paramsconst method = Astro.request.method; // the raw Requestconst token = Astro.cookies.get('session')?.value; // typed cookie accessconst { id } = Astro.params; // dynamic route params---<p>Searching for {q}</p>Astro.requestคือRequestมาตรฐาน — headers, method และawait Astro.request.formData()หรือ.json()สำหรับ bodyAstro.urlคือURLที่ parse แล้ว — pathname และsearchParamsAstro.paramsเก็บ segment แบบ dynamic ([id])Astro.cookiesอ่านและเขียน cookie ด้วย API แบบ typed (.get,.set,.delete,.has)
กำหนดรูปแบบ response
หัวข้อที่มีชื่อว่า “กำหนดรูปแบบ response”โดย default หน้าจะ return HTML พร้อม status 200 คุณควบคุม response ผ่าน Astro.response (ตั้ง status และ headers) หรือ return Response ตรง ๆ:
---export const prerender = false;const user = Astro.cookies.get('session')?.value;
// Not logged in? Redirect.if (!user) return Astro.redirect('/login');
// Set a custom header on the HTML response.Astro.response.headers.set('Cache-Control', 'private, max-age=0');---<h1>Your dashboard</h1>Astro.redirect('/login') return redirect Response; Astro.response.headers แก้ header ที่ส่งออก; และคุณ return new Response(...) เพื่อคุมเต็มที่ได้ (หน้า 404, custom status) นี่คือ model Request/Response เดียวกับที่ทั้ง web platform ใช้ — Astro ไม่ได้คิดของตัวเองขึ้นมาใหม่