Astro cheatsheet
Astro: Islands, endpoints and deployment
6 common Astro tasks.
Add an interactive component
A client: directive hydrates a framework component. Without one, it renders as plain HTML with no JavaScript.
---
import Counter from "../components/Counter.jsx";
---
<Counter client:load />
<Counter client:visible /> <!-- hydrate when scrolled into view -->
Read environment variables
Public variables start with PUBLIC_. Others are available only on the server.
const apiUrl = import.meta.env.PUBLIC_API_URL;
const secret = import.meta.env.API_SECRET; // server only
Create an API endpoint
A .ts file in src/pages exports a function per HTTP method.
// src/pages/api/hello.json.ts
export const GET = () =>
new Response(JSON.stringify({ message: "Hello" }), {
headers: { "Content-Type": "application/json" },
});
Render on the server
Add an adapter to render pages on demand. Choose the one for your host.
npx astro add node
Render a page on demand
In a mostly static site, mark a page to render per request.
---
export const prerender = false;
---
Configure the site
Set the site URL, which is needed for the sitemap and absolute URLs.
// astro.config.mjs
import { defineConfig } from "astro/config";
export default defineConfig({
site: "https://www.example.com",
});