Skip to main content
CodeSpeedTest
Languages
Start TypingJump into a test — pick any languageAdaptive TrainingUnlock chars as you master themPractice DrillsFocused sessions targeting weak spotsDaily ChallengesNew coding challenges every dayRace ModeCompete against others in real timeAI OpponentRace against an AI at your WPM levelTournamentsLive coding speed tournamentsArcade GamesZType, Overkill Survival, Glyphica & moreGamificationXP, coins, badges & quests
LeaderboardGlobal rankings for every languageCertificatesEarn verifiable Bronze / Silver / Gold certsActivityDaily streaks & historical analyticsProfileYour stats, badges & achievements
Browse Languages500+ languages with real code examplesBlogTips, guides & deep divesFree ToolsWPM calculator, typing speed report & moreFAQCommon questions answeredGetting StartedNew to CodeSpeedTest?AboutOur story & missionSupportGet help — Pro users get priorityContactGet in touch with the team
Pricing
  1. Home
  2. /
  3. Learn
  4. /
  5. Astro

Learn Astro - 10 Code Examples & CST Typing Practice Test

Astro is a modern, content-focused web framework designed for building fast, optimized websites using a 'bring your own framework' philosophy and a server-first, zero-JS-by-default approach.

View all 10 Astro code examples →
Astro Counter ComponentAstro Counter with Max LimitAstro Counter with Double StepAstro Counter with HistoryAstro Counter with Auto-IncrementAstro Counter with Conditional ThemeAstro Counter with Lambda HandlersAstro Counter with Custom StepAstro Counter with Dark Mode Toggle OnlyAstro Counter with Combined Features

Learn ASTRO with Real Code Examples

Updated Nov 21, 2025

Explain

Astro helps developers build highly performant websites with minimal JavaScript shipped to the client.

It supports mixing multiple UI frameworks (React, Vue, Svelte, etc.) in one project.

Astro emphasizes server rendering, static generation, and island architecture for partial hydration.

Core Features

File-based routing

Static Site Generation (SSG)

SSR optional mode

Components as server-rendered templates

Built-in content collections

Basic Concepts Overview

Astro components (.astro files)

Islands & partial hydration

Routing via filesystem

Layouts & content collections

Markdown & MDX integration

Project Structure

src/pages - routes

src/components - components

src/layouts - page layouts

src/content - content collections

astro.config.mjs - framework config

Building Workflow

Create .astro or framework components

Use server-only code by default

Hydrate specific UI islands using directives

Use Astro’s content collection for structured content

Build and deploy to static hosting or SSR platform

Difficulty Use Cases

Beginner: blogs, static pages

Intermediate: docs sites with MDX

Advanced: SSR-enabled hybrid sites

Expert: multi-framework islands

Community: theme & template creation

Comparisons

More performance-focused than Next.js

Simpler than Nuxt or SvelteKit

Better for static sites than React-based tools

More flexible in framework usage

Less suited for complex apps than full-stack frameworks

Versioning Timeline

2021 - Astro 1.0 early release

2022 - Astro 1.0 stable

2023 - Astro 2.0 with content collections

2024 - Significant SSR improvements

2025 - Multi-runtime stabilization & new integrations

Glossary

Islands: isolated interactive components

Hydration: turning HTML into an interactive component

Frontmatter: server-side code block in Astro

Adapters: enable SSR on different platforms

Content Collections: schema-validated content system

Installation Setup

`npm create astro@latest`

Choose template: blog, docs, minimal, etc.

Start dev server with `npm run dev`

Configure integrations (React/Vue/Svelte)

Deploy to platforms like Vercel, Netlify, Cloudflare

Environment Setup

Install Node.js

Create Astro project

Choose framework integrations

Configure MDX if needed

Set up adapter for SSR

Config Files

astro.config.mjs - main config

tsconfig.json - TypeScript support

package.json - scripts/dependencies

tailwind.config.js - if using Tailwind

mdx.config.js - if using MDX

Cli Commands

`npm create astro` - new project

`npm run dev` - start dev server

`npm run build` - build site

`npm run preview` - preview build

`npx astro add` - add integrations

Internationalization

Community i18n integrations

Static i18n via routing

MDX localization

SSR-powered locale switching

URL-based language segmentation

Accessibility

Semantic HTML-first approach

Low JS = fewer accessibility pitfalls

Astro components encourage ARIA-friendly patterns

Supports framework-level accessibility

Optimized static sites improve navigation

Ui Styling

Tailwind CSS

CSS Modules

Sass

Vanilla CSS

Framework-specific styling inside islands

State Management

Local state inside islands

React/Vue/Svelte state libraries

Signals (Solid/Preact) for islands

No global state needed for static content

Store JS only inside interactive components

Data Management

Astro `fetch()` in server context

Content collections for structured data

Markdown & MDX data ingestion

API endpoints with Astro server functions

External CMS integrations (Sanity, Contentful, etc.)

Architecture

Server-first rendering

Island architecture for partial hydration

Hybrid SSG + SSR

File-system routing

Framework-agnostic component model

Rendering Model

Server Rendered by default

Static Generation

Partial Hydration via islands

SSR with adapters

Hybrid rendering

Architectural Patterns

Island architecture

Layout-driven pages

Content schema collections

Multi-framework component integration

Static-first pipelines

Real World Architectures

Content-driven corporate websites

Docs sites like Astro Docs

Mixed React + Svelte marketing sites

Static-first e-commerce

Multi-language international sites

Design Principles

Zero-JS by default

Content-first development

Framework-agnostic philosophy

Server-first rendering

Partial hydration for interactivity

Scalability Guide

Use SSG when possible

Add SSR only where needed

Split interactive components into islands

Use caching layers on SSR deployments

Leverage Astro’s lightweight rendering

Migration Guide

Move React/Vue sites to Astro islands

Convert pages to .astro components

Extract content into collections

Use adapters for SSR if moving from Next/Nuxt

Replace SPA routing with file-based routing

Performance Notes

Zero-JS by default ensures fast loads

Hydrate only what is interactive

Use image optimization integrations

Prefer static generation whenever possible

Cache SSR responses on the edge

Security Notes

Server code isolated from client automatically

Validate MDX or user-generated content

Sanitize dynamic HTML

Use security headers on deployment platform

Avoid leaking environment variables in islands

Monitoring Analytics

Vercel Analytics (if deployed on Vercel)

Netlify Analytics

Cloudflare Insights

Sentry for error monitoring

Third-party tools like Plausible

Code Quality

Use Prettier & ESLint

Organize components by domain

Use TypeScript inside frontmatter

Validate content schemas

Avoid unnecessary hydration

Practical Examples

Markdown-powered blog

Documentation site using MDX

Marketing homepage with React islands

Static e-commerce catalog

Hybrid SSR + SSG product site

Troubleshooting

Check hydration directive (client:load/client:visible)

Verify framework integrations are installed

Ensure correct component paths

Fix TypeScript errors in content collections

Resolve SSR adapter mismatches

Testing Guide

Unit tests with Vitest

Component testing with @astrojs/test-utils

E2E with Playwright

Mock SSR components

Lint MDX & markdown files

Deployment Options

Static hosting (default)

Vercel (SSR adapter)

Netlify Edge

Cloudflare Pages

Deno Deploy

Tools Ecosystem

Astro CLI

Astro Integrations

Content collections

Image & markdown plugins

SSR adapters (Node, Deno, Cloudflare)

Integrations

React / Vue / Svelte / Solid

Tailwind CSS

MDX

Partytown

Preact

Productivity Tips

Keep islands small and focused

Use MDX for mixed content + components

Prefer content collections for data

Leverage Astro integrations instead of manual setup

Cache API fetches during build

Challenges

Build a personal blog

Create a landing page with islands

Develop a docs site using MDX

Integrate React + Svelte together

Publish an Astro theme

Learning Path

Learn Astro components & syntax

Understand island architecture

Use content collections

Add framework islands (React/Vue/Svelte)

Deploy SSG or SSR site

Skill Improvement Plan

Week 1: Astro basics + components

Week 2: Routing, layouts, MDX

Week 3: Islands + framework hydration

Week 4: SSR + adapters

Week 5: Optimization + deployment

Interview Questions

What is Astro and what problem does it solve?

Explain island architecture.

How does partial hydration work?

What are Astro components?

How does Astro differ from Next.js?

Cheat Sheet

`---` - frontmatter block

`client:load` - hydrate on load

`client:idle` - hydrate when idle

`client:visible` - hydrate on visibility

src/pages - routes by file path

Books

Build with Astro

The Astro Handbook

Content-Driven Sites with Astro

Mastering Astro

Astro for Web Developers

Tutorials

Astro official tutorials

Fireship Astro course

Net Ninja Astro series

Traversy Media Astro crash course

Frontend Masters Astro course

Official Docs

https://docs.astro.build

https://astro.new

Community Links

Astro Discord

GitHub Astro repository

Reddit r/astro

Stack Overflow Astro tag

Astro theme library

Community Support

Astro Discord

GitHub Discussions

Reddit r/astro

Stack Overflow Astro tag

Astro integration ecosystem

Monetization

Theme/templates marketplace

Freelance landing page builds

Docs site development

SEO-focused business websites

Astro consulting or integration services

Future Roadmap

Improved SSR performance

More official integrations

Better hydration primitives

Extended content collection features

AI-assisted content generation integrations

When Not To Use

Highly interactive dashboards

Complex SPAs requiring heavy client-side JS

Real-time apps

Apps that depend on client-side routing

Server-heavy full-stack applications

Final Summary

Astro is a performance-focused framework for content-rich websites.

It uses zero-JS-by-default and island architecture.

Supports multiple frameworks simultaneously.

Ideal for blogs, docs, and static sites.

One of the fastest-growing frontend tools.

Faq

Does Astro ship JavaScript by default?

No, JS is opt-in.

Can I use React/Vue/Svelte?

Yes, all major frameworks are supported.

Is Astro good for blogs?

It’s one of the best frameworks for content sites.

Does Astro support SSR?

Yes, with adapters.

Is Astro beginner friendly?

Very - simpler than most JS frameworks.

Code Sample Descriptions

1

Astro Counter Component

---
import Counter from '../components/Counter.jsx';
---
<html>
    <body>
        <h1>Astro Counter Page</h1>
        <Counter />
    </body>
</html>

// components/Counter.jsx
import { useState } from 'react';
export default function Counter() {
    const [count, setCount] = useState(0);
    const [isDark, setIsDark] = useState(false);
    return (
        <div className={isDark ? 'dark-theme' : 'light-theme'}>
        <h2>Counter: {count}</h2>
        <button onClick={() => setCount(count + 1)}>+</button>
        <button onClick={() => setCount(count - 1)}>-</button>
        <button onClick={() => setCount(0)}>Reset</button>
        <button onClick={() => setIsDark(!isDark)}>Toggle Theme</button>
        </div>
    );
}

A basic counter component in Astro using React with theme toggling.

Let’s Try →
2

Astro Counter with Max Limit

---
import MaxCounter from '../components/MaxCounter.jsx';
---
<html>
    <body>
        <h1>Astro Max Counter</h1>
        <MaxCounter max={5} />
    </body>
</html>

// components/MaxCounter.jsx
import { useState } from 'react';
export default function MaxCounter({ max }) {
    const [count, setCount] = useState(0);
    return (
        <div>
        <h2>Counter: {count}</h2>
        <button onClick={() => count < max && setCount(count + 1)}>+</button>
        <button onClick={() => setCount(count - 1)}>-</button>
        <button onClick={() => setCount(0)}>Reset</button>
        </div>
    );
}

Counter stops incrementing after reaching a maximum value in Astro using React.

Let’s Try →
3

Astro Counter with Double Step

---
import StepCounter from '../components/StepCounter.jsx';
---
<html>
    <body>
        <h1>Astro Step Counter</h1>
        <StepCounter step={2} />
    </body>
</html>

// components/StepCounter.jsx
import { useState } from 'react';
export default function StepCounter({ step }) {
    const [count, setCount] = useState(0);
    return (
        <div>
        <h2>Counter: {count}</h2>
        <button onClick={() => setCount(count + step)}>+</button>
        <button onClick={() => setCount(count - step)}>-</button>
        <button onClick={() => setCount(0)}>Reset</button>
        </div>
    );
}

A counter component in Astro that increments/decrements by 2 each time.

Let’s Try →
4

Astro Counter with History

---
import HistoryCounter from '../components/HistoryCounter.jsx';
---
<html>
    <body>
        <h1>Astro Counter History</h1>
        <HistoryCounter />
    </body>
</html>

// components/HistoryCounter.jsx
import { useState } from 'react';
export default function HistoryCounter() {
    const [count, setCount] = useState(0);
    const [history, setHistory] = useState([]);
    const update = (action) => { setHistory([...history, action]); };
    return (
        <div>
        <h2>Counter: {count}</h2>
        <div>History: {history.join(', ')}</div>
        <button onClick={() => { setCount(count + 1); update('Increment'); }}>+</button>
        <button onClick={() => { setCount(count - 1); update('Decrement'); }}>-</button>
        <button onClick={() => { setCount(0); update('Reset'); }}>Reset</button>
        </div>
    );
}

A counter component in Astro that logs each action to a history array.

Let’s Try →
5

Astro Counter with Auto-Increment

---
import AutoCounter from '../components/AutoCounter.jsx';
---
<html>
    <body>
        <h1>Astro Auto Counter</h1>
        <AutoCounter />
    </body>
</html>

// components/AutoCounter.jsx
import { useState, useEffect } from 'react';
export default function AutoCounter() {
    const [count, setCount] = useState(0);
    useEffect(() => { const interval = setInterval(() => setCount(c => c + 1), 1000); return () => clearInterval(interval); }, []);
    return <h2>Counter: {count}</h2>;
}

A counter in Astro that increments automatically every second using React useEffect.

Let’s Try →
6

Astro Counter with Conditional Theme

---
import ThemeCounter from '../components/ThemeCounter.jsx';
---
<html>
    <body>
        <h1>Astro Conditional Theme Counter</h1>
        <ThemeCounter />
    </body>
</html>

// components/ThemeCounter.jsx
import { useState } from 'react';
export default function ThemeCounter() {
    const [count, setCount] = useState(0);
    const isDark = count % 2 === 0;
    return (
        <div className={isDark ? 'dark-theme' : 'light-theme'}>
        <h2>Counter: {count}</h2>
        <button onClick={() => setCount(count + 1)}>+</button>
        <button onClick={() => setCount(count - 1)}>-</button>
        <button onClick={() => setCount(0)}>Reset</button>
        </div>
    );
}

A counter that automatically switches theme based on even/odd count in Astro.

Let’s Try →
7

Astro Counter with Lambda Handlers

---
import LambdaCounter from '../components/LambdaCounter.jsx';
---
<html>
    <body>
        <h1>Astro Lambda Counter</h1>
        <LambdaCounter />
    </body>
</html>

// components/LambdaCounter.jsx
import { useState } from 'react';
export default function LambdaCounter() {
    const [count, setCount] = useState(0);
    return (
        <div>
        <h2>Counter: {count}</h2>
        <button onClick={() => setCount(count + 1)}>+</button>
        <button onClick={() => setCount(count - 1)}>-</button>
        <button onClick={() => setCount(0)}>Reset</button>
        </div>
    );
}

Uses inline arrow functions for counter operations in Astro React component.

Let’s Try →
8

Astro Counter with Custom Step

---
import StepCounter from '../components/StepCounter.jsx';
---
<html>
    <body>
        <h1>Astro Custom Step Counter</h1>
        <StepCounter step={3} />
    </body>
</html>

// components/StepCounter.jsx
import { useState } from 'react';
export default function StepCounter({ step }) {
    const [count, setCount] = useState(0);
    return (
        <div>
        <h2>Counter: {count}</h2>
        <button onClick={() => setCount(count + step)}>+</button>
        <button onClick={() => setCount(count - step)}>-</button>
        <button onClick={() => setCount(0)}>Reset</button>
        </div>
    );
}

Counter increments or decrements by a custom step value passed as prop.

Let’s Try →
9

Astro Counter with Dark Mode Toggle Only

---
import DarkOnlyCounter from '../components/DarkOnlyCounter.jsx';
---
<html>
    <body>
        <h1>Astro Dark Mode Counter</h1>
        <DarkOnlyCounter />
    </body>
</html>

// components/DarkOnlyCounter.jsx
import { useState } from 'react';
export default function DarkOnlyCounter() {
    const [isDark, setIsDark] = useState(false);
    return (
        <div className={isDark ? 'dark-theme' : 'light-theme'}>
        <h2>Counter: 0</h2>
        <button onClick={() => setIsDark(!isDark)}>Toggle Theme</button>
        </div>
    );
}

A counter where only the theme can be toggled, count is static.

Let’s Try →
10

Astro Counter with Combined Features

---
import FullCounter from '../components/FullCounter.jsx';
---
<html>
    <body>
        <h1>Astro Full Counter</h1>
        <FullCounter step={2} autoIncrement={true} />
    </body>
</html>

// components/FullCounter.jsx
import { useState, useEffect } from 'react';
export default function FullCounter({ step, autoIncrement }) {
    const [count, setCount] = useState(0);
    const [history, setHistory] = useState([]);
    const [isDark, setIsDark] = useState(false);
    const updateHistory = (action) => setHistory([...history, action]);
    useEffect(() => { if(autoIncrement) { const i = setInterval(() => { setCount(c => { updateHistory('Auto increment'); return c + step; }); }, 1000); return () => clearInterval(i); } }, []);
    return (
        <div className={isDark ? 'dark-theme' : 'light-theme'}>
        <h2>Counter: {count}</h2>
        <div>History: {history.join(', ')}</div>
        <button onClick={() => { setCount(count + step); updateHistory('Increment'); }}>+</button>
        <button onClick={() => { setCount(count - step); updateHistory('Decrement'); }}>-</button>
        <button onClick={() => { setCount(0); updateHistory('Reset'); }}>Reset</button>
        <button onClick={() => setIsDark(!isDark)}>Toggle Theme</button>
        </div>
    );
}

A full-featured Astro counter: history, step, auto-increment, and theme toggle.

Let’s Try →

Frequently Asked Questions about Astro

What is Astro?

Astro is a modern, content-focused web framework designed for building fast, optimized websites using a 'bring your own framework' philosophy and a server-first, zero-JS-by-default approach.

What are the primary use cases for Astro?

Marketing and landing pages. Blogs and documentation sites. Static content-heavy websites. Hybrid static + server-rendered content. Sites using multiple UI frameworks together

What are the strengths of Astro?

Extremely fast performance. Little to no JavaScript shipped by default. Supports multiple frameworks together. Great for SEO-heavy sites. Best-in-class markdown ecosystem

What are the limitations of Astro?

Not ideal for full dynamic web apps. Requires islands for interactivity. SSR is available but not as feature-rich as full-stack frameworks. Tooling ecosystem smaller than React/Next.js. Complex for highly interactive dashboards or apps

How can I practice Astro typing speed?

CodeSpeedTest offers 10+ real Astro code examples for typing practice. You can measure your WPM, track accuracy, and improve your coding speed with guided exercises.

Learn Other Programming Languages

CReactPythonC++RustTypeScriptKotlinPHPJavaC#RubyMqlCqlN1qlCypherGremlinPartiqlHaskellElixirFsharpView all languages →
CodeSpeedTest

Improve your coding speed, code accuracy, and programming syntax WPM with practice sessions across 500+ programming languages.

Quick Links

HomeAboutFeaturesGetting StartedLanguages

Legal & Support

Pro ⚡ PricingContactPrivacy PolicyTerms of Service

Connect

CodeSpeedTest on GitHubCodeSpeedTest on TwitterEmail CodeSpeedTest

© 2026 CodeSpeedTest. All rights reserved.