Astro SSR: Server-Side Rendering และ Hybrid Rendering
#astro12 เม.ย. 2569
Astro Rendering Modes
Astro รองรับ 3 rendering modes
- Static (SSG) — build time rendering (default)
- Server (SSR) — request time rendering
- Hybrid — ผสมทั้งสองแบบ
เปิดใช้ SSR
// astro.config.mjs
import { defineConfig } from 'astro/config';
import node from '@astrojs/node';
export default defineConfig({
output: 'server',
adapter: node({ mode: 'standalone' })
});
Hybrid Mode
export default defineConfig({
output: 'hybrid' // ส่วนใหญ่ static แต่บางหน้า SSR
});
SSR Page
---
// src/pages/dashboard.astro
export const prerender = false; // บังคับ SSR
const user = Astro.locals.user;
if (!user) return Astro.redirect('/login');
const data = await fetch(`/api/dashboard/${user.id}`).then(r => r.json());
---
<h1>Dashboard ของ {user.name}</h1>
<p>ข้อมูล: {JSON.stringify(data)}</p>
Static Page ใน Hybrid Mode
---
// src/pages/about.astro
export const prerender = true; // บังคับ static
---
<h1>เกี่ยวกับเรา</h1>
Cookies และ Headers
---
// อ่าน cookie
const token = Astro.cookies.get('token')?.value;
// set cookie
Astro.cookies.set('theme', 'dark', {
httpOnly: true,
secure: true,
maxAge: 60 * 60 * 24 * 7
});
// อ่าน request headers
const userAgent = Astro.request.headers.get('user-agent');
---
Adapters
# Cloudflare
npx astro add cloudflare
# Vercel
npx astro add vercel
# Node.js
npx astro add node
# Netlify
npx astro add netlify
Cloudflare Adapter
import { defineConfig } from 'astro/config';
import cloudflare from '@astrojs/cloudflare';
export default defineConfig({
output: 'server',
adapter: cloudflare()
});
สรุป
Astro SSR เหมาะกับหน้าที่ต้องการข้อมูล real-time หรือ authentication ส่วน Hybrid mode ช่วยให้ได้ทั้ง performance ของ static และ flexibility ของ SSR ครับ