Svelte
AstraCMS integration for Svelte and SvelteKit
The @astracms/svelte package provides Svelte stores and SvelteKit utilities for AstraCMS.
Installation
npm install @astracms/sveltepnpm add @astracms/svelteyarn add @astracms/sveltebun add @astracms/svelteEnvironment Variables
Create a .env file in your SvelteKit project:
VITE_ASTRACMS_API_KEY=your_api_key_hereConfiguration
Create a client instance:
import { createAstraCMSClient } from '@astracms/svelte'
export const astracms = createAstraCMSClient({
apiKey: import.meta.env.VITE_ASTRACMS_API_KEY,
})SvelteKit Usage
Server-Side Loading
import { astracms } from '$lib/astracms'
export async function load() {
const posts = await astracms.getPosts()
return { posts }
}<script>
export let data
</script>
<ul>
{#each data.posts as post}
<li>{post.title}</li>
{/each}
</ul>Single Post
import { astracms } from '$lib/astracms'
import { error } from '@sveltejs/kit'
export async function load({ params }) {
const post = await astracms.getPost(params.slug)
if (!post) {
throw error(404, 'Post not found')
}
return { post }
}<script>
export let data
</script>
<article>
<h1>{data.post.title}</h1>
{@html data.post.content}
</article>Svelte Stores
For client-side reactivity:
<script>
import { postsStore } from '@astracms/svelte'
import { astracms } from '$lib/astracms'
const posts = postsStore(astracms)
</script>
{#if $posts.loading}
<p>Loading...</p>
{:else if $posts.error}
<p>Error: {$posts.error.message}</p>
{:else}
<ul>
{#each $posts.data as post}
<li>{post.title}</li>
{/each}
</ul>
{/if}Filtering Posts
The getPosts method supports filtering options:
import { astracms } from '$lib/astracms'
export async function load() {
const posts = await astracms.getPosts({
categories: ['technology', 'tutorials'], // Filter by categories
excludeCategories: ['internal'], // Exclude categories
tags: ['javascript', 'react'], // Filter by tags
excludeTags: ['draft'], // Exclude tags
query: 'search term', // Search query
format: 'html', // Content format
limit: 10, // Max posts
page: 1, // Pagination
})
return { posts }
}Available Options:
| Option | Type | Description |
|---|---|---|
categories | string[] | Filter by category slugs |
excludeCategories | string[] | Exclude category slugs |
tags | string[] | Filter by tag slugs |
excludeTags | string[] | Exclude tag slugs |
query | string | Search query |
format | 'html' | 'markdown' | Content format |
limit | number | Max posts to return |
page | number | Page number |
Last updated on