AstraCMS

Svelte

AstraCMS integration for Svelte and SvelteKit

The @astracms/svelte package provides Svelte stores and SvelteKit utilities for AstraCMS.

Installation

npm install @astracms/svelte
pnpm add @astracms/svelte
yarn add @astracms/svelte
bun add @astracms/svelte

Environment Variables

Create a .env file in your SvelteKit project:

.env
VITE_ASTRACMS_API_KEY=your_api_key_here

Configuration

Create a client instance:

src/lib/astracms.ts
import { createAstraCMSClient } from '@astracms/svelte'

export const astracms = createAstraCMSClient({
  apiKey: import.meta.env.VITE_ASTRACMS_API_KEY,
})

SvelteKit Usage

Server-Side Loading

src/routes/blog/+page.server.ts
import { astracms } from '$lib/astracms'

export async function load() {
  const posts = await astracms.getPosts()
  return { posts }
}
src/routes/blog/+page.svelte
<script>
  export let data
</script>

<ul>
  {#each data.posts as post}
    <li>{post.title}</li>
  {/each}
</ul>

Single Post

src/routes/blog/[slug]/+page.server.ts
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 }
}
src/routes/blog/[slug]/+page.svelte
<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:

src/routes/blog/+page.server.ts
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:

OptionTypeDescription
categoriesstring[]Filter by category slugs
excludeCategoriesstring[]Exclude category slugs
tagsstring[]Filter by tag slugs
excludeTagsstring[]Exclude tag slugs
querystringSearch query
format'html' | 'markdown'Content format
limitnumberMax posts to return
pagenumberPage number

Last updated on

On this page