ข้ามไปเนื้อหาหลัก

Category: guide

Astro SSR — output server/hybrid mode

คู่มือ Astro SSR mode — เปิด server rendering, adapters (Node.js, Cloudflare, Vercel), และ hybrid (บาง page static บาง page server)

· อ่านประมาณ 2 นาที

สารบัญ

Static vs SSR vs Hybrid

modeoutputใช้เมื่อ
static (default)HTML filessite ไม่ต้องการ dynamic data
serverrender per requestทุก page dynamic
hybridmix ทั้งสองบาง page static บาง page dynamic

ตั้งค่า

// astro.config.mjs
import { defineConfig } from 'astro/config';
import node from '@astrojs/node';

export default defineConfig({
  output:  'server',  // หรือ 'hybrid'
  adapter: node({ mode: 'standalone' }),
});
npm install @astrojs/node

Adapters

# Node.js (self-hosted)
npm install @astrojs/node

# Cloudflare Pages/Workers
npm install @astrojs/cloudflare

# Vercel
npm install @astrojs/vercel

# Netlify
npm install @astrojs/netlify

Dynamic Page

---
// src/pages/products/[id].astro
// ไม่มี getStaticPaths → render on-demand
const { id } = Astro.params;
const product = await db.query('SELECT * FROM products WHERE id = ?', [id]);

if (!product) return Astro.redirect('/404');
---

<h1>{product.name}</h1>
<p>฿{product.price.toLocaleString()}</p>

Hybrid Mode — Static by default

---
// src/pages/blog/[slug].astro — static
// ไม่ต้องทำอะไร ถ้ามี getStaticPaths → static
export async function getStaticPaths() {
  const posts = await getCollection('blog');
  return posts.map((p) => ({ params: { slug: p.slug } }));
}
---
---
// src/pages/api/submit.astro — server
export const prerender = false;  // บอกชัดว่า dynamic

if (Astro.request.method === 'POST') {
  const data = await Astro.request.formData();
  // process form...
}
---

Cookies และ Headers

---
// อ่าน cookie
const token = Astro.cookies.get('auth-token')?.value;

// set cookie
Astro.cookies.set('theme', 'dark', {
  httpOnly: false,
  maxAge: 60 * 60 * 24 * 365,  // 1 ปี
  path: '/',
});

// set response header
Astro.response.headers.set('Cache-Control', 's-maxage=3600');
---

Request Object

---
const { method, url, headers } = Astro.request;
const userAgent = headers.get('user-agent');
const ip        = Astro.clientAddress;  // IP จริงของ visitor
---

ข้อควรระวัง

  • import.meta.env ใช้ได้ปกติ แต่ server-side secrets ไม่ expose ออก client
  • SSR render ทุก request — cache ใน CDN หรือ memory ถ้า page heavy
  • ใช้ export const prerender = true ใน hybrid mode เพื่อ force static บาง page