Three.js with Astro

Zero-JS by default — ship only the 3D you need with Astro

Integration Guide

Overview

Astro's island architecture is perfect for Three.js: ship static HTML everywhere else and hydrate only the canvas components that actually need JavaScript. This approach dramatically improves Core Web Vitals while still delivering stunning 3D.

Quick Start

npm install three @astrojs/react @react-three/fiber @react-three/drei
---
// src/pages/index.astro
import ThreeScene from '../components/ThreeScene'
---

<html>
  <body>
    <h1>My Astro Site</h1>
    <!-- client:only ensures Three.js only runs in the browser -->
    <ThreeScene client:only="react" />
  </body>
</html>

// src/components/ThreeScene.tsx (React island)
import { Canvas } from '@react-three/fiber'
import { OrbitControls, Environment } from '@react-three/drei'

export default function ThreeScene() {
  return (
    <Canvas style={{ height: '500px' }}>
      <Environment preset="sunset" />
      <mesh>
        <torusKnotGeometry args={[1, 0.3, 128, 16]} />
        <meshStandardMaterial color="coral" roughness={0.2} metalness={0.8} />
      </mesh>
      <OrbitControls autoRotate />
    </Canvas>
  )
}

Pros

  • Zero JS shipped by default — best-in-class performance
  • client:only directive perfectly isolates Three.js from SSR
  • Use React, Vue, or Svelte for your 3D island components
  • Content Collections for blog/docs alongside 3D demos
  • Exceptional LCP scores possible with static shell + lazy 3D

Cons

  • Island architecture adds complexity vs. pure SPA
  • Data sharing between islands requires global state solutions
  • Build output can be complex to debug

Frequently Asked Questions

Can I use React Three Fiber inside an Astro project?

Yes. Add the @astrojs/react integration, then use <Component client:only='react' /> to render your R3F Canvas as a client-only island.

Why is client:only better than client:load for Three.js in Astro?

Three.js needs browser APIs that don't exist on the server. client:only skips server rendering entirely, preventing SSR errors.

Best Use Cases

  • Documentation sites with embedded 3D demos
  • Marketing sites where SEO + 3D are equally important
  • Blogs with interactive Three.js examples
  • Agency portfolios with hero 3D animations