Web Engineering Kỹ Thuật Web · · 6 min read

Getting Started with Astro Bắt Đầu Xây Dựng Website Siêu Tốc Với Astro

Learn how to build lightning-fast websites with Astro, the modern static site generator that ships zero JavaScript by default. Hướng dẫn xây dựng website tĩnh hiệu năng vượt trội với Astro — framework hiện đại không gửi JavaScript thừa về phía client theo mặc định.

Written by Nguyen Cong Ben Nguyễn Công Ben
Getting started with Astro Framework

1. 🌐 The Modern Web Bloat Dilemma

For years, full-stack Single Page Application (SPA) frameworks like React, Next.js, and Nuxt dominated web development. While powerful for complex SaaS dashboards, using heavy client-side frameworks for content-focused websites (portfolios, engineering blogs, marketing sites, documentation) created severe performance penalties:

  • Massive JavaScript Payloads: A simple article often shipped 250KB–500KB of runtime JavaScript just to render static text and headings.
  • Hydration Tax: The browser had to download, parse, compile, and execute the entire React/Vue component tree before the page became interactive, degrading Interaction to Next Paint (INP) and Largest Contentful Paint (LCP).
  • SEO & Indexing Friction: Search crawlers had to execute client scripts to discover basic links and metadata.

Astro fundamentally rethinks this equation with a Content-First, Zero-JS by Default philosophy.


2. 🏝️ The Astro Architecture: Component Islands

Astro pioneered the Islands Architecture (conceptually coined by Jason Miller). In Astro:

  1. The entire page renders to pure, static HTML and CSS on the server at build time.
  2. Interactive components (e.g., a dynamic search bar or a language switcher) are isolated into independent “Islands”.
  3. Only these specific islands receive JavaScript runtime, hydrated on-demand based on explicit client directives:
---
// src/pages/index.astro
import Layout from '../layouts/Layout.astro';
import StaticHero from '../components/StaticHero.astro';
import InteractiveSearch from '../components/InteractiveSearch.jsx';
import ThemeToggle from '../components/ThemeToggle.svelte';
---

<Layout title="Lightning Fast Web">
  <!-- 100% Pure HTML (0 KB JavaScript) -->
  <StaticHero />

  <!-- Hydrates only when visible in the user's viewport -->
  <InteractiveSearch client:visible />

  <!-- Hydrates when the browser is idle -->
  <ThemeToggle client:idle />
</Layout>

3. 🛡️ Type-Safe Content Collections with Zod

Astro includes native, schema-validated content pipelines via astro:content. Every markdown or MDX document is validated against strict TypeScript/Zod schemas during compilation, preventing broken frontmatter and missing metadata from ever reaching production:

// src/content.config.ts
import { defineCollection, z } from 'astro:content';
import { glob } from 'astro/loaders';

const postsCollection = defineCollection({
  loader: glob({ pattern: '**/*.md', base: './src/content/posts' }),
  schema: z.object({
    title: z.string(),
    description: z.string(),
    pubDate: z.coerce.date(),
    author: z.string().default('Nguyen Cong Ben'),
    tags: z.array(z.string()),
    draft: z.boolean().default(false),
  }),
});

export const collections = { posts: postsCollection };

4. ⚡ Step-by-Step Quick Start

Getting started with an Astro project takes under a minute:

# 1. Initialize modern Astro project
npm create astro@latest my-astro-portfolio

# 2. Add Tailwind CSS and React integration
npx astro add tailwind react

# 3. Start high-speed local dev server with hot module replacement
npm run dev

5. 📊 Production Benchmarks & Summary

By stripping away unneeded client JavaScript, Astro sites consistently achieve:

  • 100/100 Lighthouse Performance out of the box.
  • Sub-500ms First Contentful Paint (FCP) on 4G mobile networks.
  • Zero Hydration Mismatch Errors, ensuring resilient, accessible user experiences.

For technical portfolios, content hubs, and engineering blogs, Astro represents the state of the art in modern static web architecture.

1. 🌐 Vấn Nạn Quá Tải JavaScript Trên Web Hiện Đại

Trong nhiều năm, các framework Single Page Application (SPA) như React, Next.js và Nuxt đã thống trị thế giới phát triển web. Mặc dù rất mạnh mẽ cho các ứng dụng SaaS phức tạp, việc áp dụng các framework nặng nề này cho các trang web thiên về nội dung (portfolio cá nhân, blog kỹ thuật, trang tài liệu) lại gây ra những tổn thất hiệu năng nghiêm trọng:

  • Dung lượng JavaScript quá lớn: Một bài viết văn bản đơn giản thường phải tải kèm từ 250KB–500KB mã JavaScript chỉ để hiển thị tiêu đề và chữ.
  • Gánh nặng Hydration: Trình duyệt phải tải, biên dịch và thực thi toàn bộ cây component React/Vue trước khi trang web có thể tương tác, làm suy giảm chỉ số LCP (Thời gian hiển thị nội dung lớn nhất)INP (Độ trễ tương tác).
  • Bất lợi về SEO: Robot tìm kiếm của Google phải tốn tài nguyên chạy mã JavaScript phía client để thu thập liên kết.

Astro ra đời để định nghĩa lại tiêu chuẩn này với triết lý: Ưu Tiên Nội Dung & Mặc Định Không Gửi JavaScript (Zero-JS by Default).


2. 🏝️ Kiến Trúc Đảo (Islands Architecture) Trong Astro

Astro tiên phong ứng dụng mô hình Kiến Trúc Đảo (Islands Architecture). Trong Astro:

  1. Toàn bộ trang web được render thành mã HTML và CSS thuần túy trên máy chủ ngay lúc build.
  2. Các thành phần cần tương tác động (như thanh tìm kiếm, nút chuyển đổi ngôn ngữ) được cô lập thành các “hòn đảo” độc lập.
  3. Trình duyệt chỉ tải JavaScript cho đúng các thành phần này khi thực sự cần thiết thông qua các chỉ thị client:*:
---
// src/pages/index.astro
import Layout from '../layouts/Layout.astro';
import StaticHero from '../components/StaticHero.astro';
import InteractiveSearch from '../components/InteractiveSearch.jsx';
import ThemeToggle from '../components/ThemeToggle.svelte';
---

<Layout title="Website Siêu Tốc">
  <!-- 100% HTML Tĩnh (0 KB JavaScript thừa) -->
  <StaticHero />

  <!-- Chỉ nạp JS khi phần tử xuất hiện trong tầm nhìn màn hình -->
  <InteractiveSearch client:visible />

  <!-- Nạp JS khi trình duyệt rảnh rỗi -->
  <ThemeToggle client:idle />
</Layout>

3. 🛡️ Quản Lý Nội Dung An Toàn Kiểu Dữ Liệu Với Zod

Astro tích hợp sẵn luồng xử lý nội dung astro:content. Mọi bài viết Markdown hoặc MDX đều được kiểm tra nghiêm ngặt bằng TypeScript và Zod Schema ngay lúc build, loại bỏ hoàn toàn nguy cơ lỗi thiếu metadata hoặc sai định dạng ngày tháng:

// src/content.config.ts
import { defineCollection, z } from 'astro:content';
import { glob } from 'astro/loaders';

const postsCollection = defineCollection({
  loader: glob({ pattern: '**/*.md', base: './src/content/posts' }),
  schema: z.object({
    title: z.string(),
    description: z.string(),
    pubDate: z.coerce.date(),
    author: z.string().default('Nguyễn Công Ben'),
    tags: z.array(z.string()),
    draft: z.boolean().default(false),
  }),
});

export const collections = { posts: postsCollection };

4. ⚡ Các Bước Khởi Tạo Dự Án Nhanh

Khởi tạo một dự án Astro hiện đại chỉ mất chưa đầy một phút:

# 1. Khởi tạo dự án Astro mới nhất
npm create astro@latest my-astro-portfolio

# 2. Tích hợp Tailwind CSS và React
npx astro add tailwind react

# 3. Chạy môi trường phát triển siêu tốc
npm run dev

5. 📊 Đo Lường Hiệu Năng & Tổng Kết

Nhờ loại bỏ mã JavaScript thừa thãi, các website xây dựng bằng Astro đạt được:

  • Điểm tuyệt đối 100/100 Lighthouse Performance ngay từ cấu hình mặc định.
  • Thời gian hiển thị nội dung đầu tiên (FCP) dưới 500ms trên mạng di động 4G.
  • Không xảy ra lỗi bất đồng bộ Hydration, mang lại trải nghiệm truy cập mượt mà và thân thiện với SEO.

Đối với portfolio lập trình viên và blog kỹ thuật, Astro chính là sự lựa chọn hàng đầu của kỹ thuật web hiện đại.