Svelte Integration Guide

A straightforward guide to set up JustCMS in your Svelte project

Getting Started with JustCMS and Svelte

JustCMS integration for Svelte provides a straightforward way to add content management capabilities to your Svelte applications. This integration is designed to be simple yet powerful, offering a type-safe approach to working with your content.

Key Features

TypeScript Support

Fully typed structures for all API responses ensuring type safety

Single Module Architecture

All JustCMS API calls are contained in one easy-to-manage module

Environment-based Configuration

Simple setup using environment variables for API token and project ID

Comprehensive API Coverage

Access to categories, pages, menus, and more through clean interfaces

Prerequisites

Before you begin integrating JustCMS with your Svelte project, make sure you have:

  • A Svelte or SvelteKit project set up
  • TypeScript configured in your project
  • Your JustCMS API token
  • Your JustCMS project ID

Integration Overview

The integration is built around a single module that wraps the JustCMS public API endpoints. This module provides a clean interface for:

  • Fetching categories and organizing content
  • Retrieving pages with filtering and pagination
  • Accessing specific pages by their slugs
  • Managing menus and navigation

Module Architecture

The integration follows a simple architecture where all functionality is exposed through a createJustCms function. This function creates an instance of the JustCMS client, configured with your project settings.

import { createJustCms } from '$lib/justCms';

// Create an instance of the JustCMS client
const justCms = createJustCms();

Type Safety

The TypeScript integration ensures you get:

  • Autocomplete suggestions for all API methods
  • Type checking for API parameters
  • Properly typed response data
  • Compile-time error detection

Benefits of Single Module Architecture

Easy Maintenance

All CMS-related code is centralized in one location

Simple Updates

Update the integration by modifying a single file

Consistent Usage

Standardized approach to accessing CMS features across your application

Reduced Complexity

No need to manage multiple imports or dependencies

Installation and Setup Guide for JustCMS in Svelte

Setting up JustCMS in your Svelte project is a straightforward process that only takes a few minutes. Let's walk through the essential steps to get you started.

Prerequisites

Existing Svelte/SvelteKit Project

Make sure you have a working Svelte project set up with TypeScript support

JustCMS Account

You'll need your API token and project ID from your JustCMS dashboard

Installation Steps

Follow these simple steps to install and configure JustCMS in your Svelte project:

1. Add the Module File

Copy justCms.ts into your project's src/lib directory

2. Set Up Environment Variables

Create a .env file to store your JustCMS credentials

3. Configure TypeScript

Ensure your project is properly configured for TypeScript

Environment Configuration

Create a .env file in your project's root directory. This file will store your JustCMS credentials securely.

PUBLIC_JUSTCMS_TOKEN=YOUR_JUSTCMS_API_TOKEN
PUBLIC_JUSTCMS_PROJECT=YOUR_JUSTCMS_PROJECT_ID

Important Note: In SvelteKit, environment variables that start with PUBLIC_ are accessible on the client side. This prefix is required for the JustCMS integration to work properly.

Verifying Your Installation

To verify that everything is set up correctly, you can create a simple test component:

<script lang="ts">
  import { createJustCms } from '$lib/justCms';
  
  const justCms = createJustCms();
  console.log('JustCMS instance created successfully');
</script>

Common Setup Issues

Environment Variables Not Loading

Make sure your .env file is in the root directory and properly formatted

TypeScript Errors

Verify that your tsconfig.json includes the necessary compiler options

Import Errors

Check that the path to justCms.ts is correct in your import statements

With these steps completed, your Svelte project is now ready to use JustCMS. You can proceed with implementing the various features and functions provided by the integration.

Next Steps

After completing the installation and setup, you can start using JustCMS functions to fetch your content. Try retrieving categories or pages to ensure everything works as expected.

Basic Usage and Implementation

Getting started with JustCMS in your Svelte project is straightforward. The main entry point is the createJustCms function, which provides access to all the core features. Let's look at how to implement the most common functionalities.

Setting Up the JustCMS Instance

import { createJustCms } from '$lib/justCms';

// Create an instance of JustCMS
const justCms = createJustCms();

Once you have created the JustCMS instance, you can use it to fetch data from your content management system. Here are the most common implementations:

Fetching Categories

Here's a simple Svelte component that fetches and displays categories:

<script lang="ts">
  import { onMount } from 'svelte';
  import { createJustCms } from '$lib/justCms';

  const justCms = createJustCms();
  let categories = [];

  onMount(async () => {
    categories = await justCms.getCategories();
  });
</script>

<div>
  <h2>Categories</h2>
  <ul>
    {#each categories as category (category.slug)}
      <li>{category.name}</li>
    {/each}
  </ul>
</div>

Working with Pages

You can fetch pages with optional filtering and pagination. Here are some common use cases:

<script lang="ts">
  import { createJustCms } from '$lib/justCms';
  
  const justCms = createJustCms();
  let pages = [];
  
  // Get all pages
  async function getAllPages() {
    pages = await justCms.getPages();
  }
  
  // Get pages from specific category
  async function getBlogPosts() {
    pages = await justCms.getPages({
      filters: { category: { slug: 'blog' } }
    });
  }
  
  // Get a single page by slug
  async function getAboutPage() {
    const page = await justCms.getPageBySlug('about-us');
  }
</script>

Fetching Menus

To retrieve and display a menu structure, use the getMenuById function:

<script lang="ts">
  import { onMount } from 'svelte';
  import { createJustCms } from '$lib/justCms';

  const justCms = createJustCms();
  let mainMenu = null;

  onMount(async () => {
    mainMenu = await justCms.getMenuById('main-menu');
  });
</script>

{#if mainMenu}
  <nav>
    <ul>
      {#each mainMenu.items as item}
        <li>
          <a hrref={item.url}>{item.label}</a>
        </li>
      {/each}
    </ul>
  </nav>
{/if}

Component-Based Integration

JustCMS functions can be easily integrated into any Svelte component

Async Data Fetching

All API calls are asynchronous and should be handled with async/await

TypeScript Support

Full type safety for all API responses and parameters

Flexible Implementation

Can be used with both client-side and server-side rendering

Remember to handle loading states and errors appropriately in your components when making API calls. It's recommended to use try/catch blocks and implement loading indicators for better user experience.

Available Functions Reference

JustCMS provides several core functions to interact with your content. Let's explore each function in detail with practical examples of how to use them in your Svelte applications.

getCategories()

The getCategories function retrieves all categories defined in your JustCMS project. This is useful for building navigation menus or category filters.

const categories = await justCms.getCategories();
// Returns an array of Category objects

getPages()

The getPages function is versatile and allows you to fetch pages with various options for filtering and pagination. You can use it to retrieve all pages or filter them by category.

Optional Parameters

filters, start, and offset for customizing your page queries

Category Filtering

Filter pages by specific category using the category slug

Pagination Support

Control the number of pages returned using start and offset

// Get all pages
const allPages = await justCms.getPages();

// Get pages from specific category
const blogPages = await justCms.getPages({
  filters: { category: { slug: 'blog' } }
});

// Get pages with pagination
const paginatedPages = await justCms.getPages({
  start: 0,
  offset: 10
});

getPageBySlug()

Use getPageBySlug when you need to retrieve a specific page's full content. This is commonly used for individual page routes in your application.

const page = await justCms.getPageBySlug('about-us');
// Returns detailed page information

getMenuById()

The getMenuById function allows you to fetch a complete menu structure including all its items. This is essential for building site navigation.

const menu = await justCms.getMenuById('main-menu');
// Returns menu structure with all items

Here's a practical example of how to implement these functions in a Svelte component:

<script lang="ts">
  import { onMount } from 'svelte';
  import { createJustCms } from '$lib/justCms';

  const justCms = createJustCms();
  let categories = [];
  let pages = [];
  let currentPage = null;
  let mainMenu = null;

  onMount(async () => {
    // Fetch multiple types of content
    categories = await justCms.getCategories();
    pages = await justCms.getPages();
    currentPage = await justCms.getPageBySlug('home');
    mainMenu = await justCms.getMenuById('main-menu');
  });
</script>

All these functions are type-safe when used with TypeScript, providing excellent autocompletion and type checking in your IDE. Remember to handle potential errors and loading states in your components when using these functions.

Type Safety

All functions include TypeScript definitions for better development experience

Error Handling

Remember to implement try/catch blocks for error handling

Loading States

Consider implementing loading indicators while data is being fetched

Utility Functions in JustCMS Svelte Integration

JustCMS provides several utility functions that make it easier to work with content blocks, images, and categories in your Svelte application. These helper functions simplify common tasks and ensure consistent handling of content across your project.

Content Block Style Checking

The isBlockHasStyle function allows you to check if a content block has a specific style applied to it. This is particularly useful when you need to apply conditional rendering based on block styles.

const isHighlighted = justCms.isBlockHasStyle(block, 'highlight');
if (isHighlighted) {
  // Apply special styling or handling
}

Image Handling Functions

getLargeImageVariant

Retrieves the large variant of an image (second variant in the array)

getFirstImage

Extracts the first image from an image block

These image utility functions help you manage different image variants and access image data more easily:

// Get large image variant
const largeVariant = justCms.getLargeImageVariant(image);

// Get first image from block
const firstImage = justCms.getFirstImage(imageBlock);

Category Management

The hasCategory function simplifies checking whether a page belongs to a specific category. This is especially useful when filtering or organizing content based on categories.

const isBlog = justCms.hasCategory(page, 'blog');
if (isBlog) {
  // Handle blog-specific logic
}

Case-Insensitive Style Checking

isBlockHasStyle performs case-insensitive comparison

Simplified Image Access

Direct access to commonly used image variants

Category Verification

Easy checking of page category membership

These utility functions are designed to make your development process smoother by handling common tasks efficiently. They reduce the amount of boilerplate code needed and ensure consistent behavior across your application.

Best Practices

Error Handling

Always check if objects exist before using utility functions

Type Safety

Utility functions maintain TypeScript type safety

Performance

Functions are optimized for minimal processing overhead

When using these utility functions, remember to implement proper error handling and null checks to ensure robust functionality in your application. The functions are designed to work seamlessly with TypeScript, providing type safety and better development experience.