API Reference
API Reference
Section titled “API Reference”This section provides detailed API documentation for all components, utilities, and configuration options available in astro-basics.
Component APIs
Section titled “Component APIs”Layout Components
Section titled “Layout Components”BaseLayout
Section titled “BaseLayout”Main layout component for all pages.
Props:
interface Props { title: string description?: string image?: string noindex?: boolean type?: 'website' | 'article'}Usage:
<BaseLayout title="Page Title" description="Page description for SEO" image="/og-image.jpg" type="article"/>Header
Section titled “Header”Site navigation header component.
Props:
interface Props { title?: string showAuth?: boolean theme?: 'light' | 'dark' | 'auto' sticky?: boolean}Content Components
Section titled “Content Components”PostCard
Section titled “PostCard”Card component for displaying blog posts and articles.
Props:
interface Props { title: string description: string pubDate: Date author: string href: string featured?: boolean image?: { url: string alt: string } tags?: string[]}Example:
<PostCard title="Getting Started with Astro" description="Learn the basics of Astro development" pubDate={new Date('2025-01-15')} author="John Doe" href="/posts/getting-started" featured={true} tags={['astro', 'tutorial']}/>Utility APIs
Section titled “Utility APIs”Content Utilities
Section titled “Content Utilities”getCollection Helper
Section titled “getCollection Helper”Enhanced content collection utilities.
import { getCollection } from 'astro:content'
// Get published posts onlyconst publishedPosts = await getCollection('posts', ({ data }) => data.publish)
// Get featured contentconst featuredPosts = await getCollection('posts', ({ data }) => data.publish && data.featured)Slugify Function
Section titled “Slugify Function”URL-safe slug generation.
import { slugify } from '#libs/content'
const slug = slugify("My Blog Post Title") // "my-blog-post-title"Truncate Function
Section titled “Truncate Function”Text truncation with word boundaries.
import { truncate } from '#libs/content'
const shortText = truncate("Long text content...", 100) // Truncated to 100 charsAuthentication APIs
Section titled “Authentication APIs”Clerk Integration
Section titled “Clerk Integration”Pre-configured authentication with Clerk.
// In API routesimport { getAuth } from '@clerk/astro/server'
export async function GET({ request }) { const { userId } = getAuth(request)
if (!userId) { return new Response('Unauthorized', { status: 401 }) }
// Authenticated route logic}Protected Routes
Section titled “Protected Routes”Middleware for route protection.
import { clerkMiddleware } from '@clerk/astro/server'
export const onRequest = clerkMiddleware()Configuration APIs
Section titled “Configuration APIs”Site Configuration
Section titled “Site Configuration”File: src/utils/site-config.ts
export const SITE_TITLE = 'Astro Basics'export const SITE_DESCRIPTION = 'Modern web development with Astro'export const SITE_URL = 'https://astro-basics.netlify.app'export const PAGINATION_COUNT = 2Content Schema
Section titled “Content Schema”File: src/content/config.ts
const postsCollection = defineCollection({ schema: z.object({ title: z.string(), pubDate: z.date(), description: z.string(), author: z.string(), breadcrumbSlug: z.string().optional(), image: z.object({ url: z.string(), alt: z.string(), caption: z.string().optional(), }).optional(), tags: z.array(z.string()).optional(), publish: z.boolean().default(false), featured: z.boolean().default(false), youtube: z.object({ id: z.string(), title: z.string().optional(), start: z.string().optional(), end: z.string().optional(), }).optional(), }),})Database APIs
Section titled “Database APIs”Supabase Client
Section titled “Supabase Client”File: src/libs/supabase.ts
import { createClient } from '@supabase/supabase-js'
const supabase = createClient( process.env.SUPABASE_URL!, process.env.SUPABASE_ANON_KEY!)
export default supabaseTurso Client
Section titled “Turso Client”File: src/libs/turso.ts
import { createClient } from '@libsql/client'
const turso = createClient({ url: process.env.TURSO_DATABASE_URL!, authToken: process.env.TURSO_AUTH_TOKEN})
export default tursoBuild Configuration
Section titled “Build Configuration”Astro Config
Section titled “Astro Config”File: astro.config.mjs
export default defineConfig({ site: process.env.SITE_URL || 'https://example.com', output: 'server', integrations: [ react(), sitemap(), embeds(), mdx(), clerk(), starlight({ title: 'Astro-Basics Guide', base: '/guide', // ... configuration }), AstroPWA({ registerType: 'autoUpdate', // ... PWA config }), ], adapter: netlify(), // or node(), vercel()})TypeScript Configuration
Section titled “TypeScript Configuration”File: tsconfig.json
{ "compilerOptions": { "strict": true, "noUncheckedIndexedAccess": true, "exactOptionalPropertyTypes": true, "paths": { "#*": ["./src/*"] } }}Environment Variables
Section titled “Environment Variables”Required Variables
Section titled “Required Variables”# AuthenticationPUBLIC_CLERK_PUBLISHABLE_KEY=pk_test_...CLERK_SECRET_KEY=sk_test_...
# Site ConfigurationSITE_URL=https://your-site.comOptional Variables
Section titled “Optional Variables”# DatabaseSUPABASE_URL=https://project.supabase.coSUPABASE_ANON_KEY=eyJhbGciOiJIUzI1NiI...
# TursoTURSO_DATABASE_URL=libsql://database.turso.ioTURSO_AUTH_TOKEN=your_token
# DeploymentASTRO_ADAPTER=netlify # or 'node', 'vercel'Error Handling
Section titled “Error Handling”API Route Patterns
Section titled “API Route Patterns”export async function GET({ request }) { try { // Route logic return new Response(JSON.stringify({ success: true, data }), { headers: { 'Content-Type': 'application/json' } }) } catch (error) { console.error('API Error:', error) return new Response(JSON.stringify({ success: false, error: error.message }), { status: 500, headers: { 'Content-Type': 'application/json' } }) }}Component Error Boundaries
Section titled “Component Error Boundaries”---let errorMessage: string | null = null
try { // Component logic that might throw} catch (error) { errorMessage = error.message}---
{errorMessage ? ( <div class="error-message"> <p>Error: {errorMessage}</p> </div>) : ( <!-- Normal component content -->)}Performance Optimization
Section titled “Performance Optimization”Image Optimization
Section titled “Image Optimization”---import { Image } from 'astro:assets'---
<Image src="/path/to/image.jpg" alt="Description" width={800} height={600} loading="lazy" decoding="async"/>Bundle Optimization
Section titled “Bundle Optimization”// Dynamic imports for code splittingconst Component = await import('#components/react/HeavyComponent')
// Conditional loadingif (someCondition) { const { heavyFunction } = await import('#utils/heavy-utils') heavyFunction()}Testing APIs
Section titled “Testing APIs”Unit Testing
Section titled “Unit Testing”import { describe, it, expect } from 'vitest'
describe('Utility Function', () => { it('should process input correctly', () => { const result = myFunction('input') expect(result).toBe('expected output') })})E2E Testing
Section titled “E2E Testing”import { test, expect } from '@playwright/test'
test('page loads correctly', async ({ page }) => { await page.goto('/') await expect(page.locator('h1')).toBeVisible()})Related Documentation
Section titled “Related Documentation”- Components - Component usage examples
- Getting Started - Setup and installation
- Configuration - Project configuration