A straightforward guide to set up JustCMS in your Svelte project
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.
Fully typed structures for all API responses ensuring type safety
All JustCMS API calls are contained in one easy-to-manage module
Simple setup using environment variables for API token and project ID
Access to categories, pages, menus, and more through clean interfaces
Before you begin integrating JustCMS with your Svelte project, make sure you have:
The integration is built around a single module that wraps the JustCMS public API endpoints. This module provides a clean interface for:
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();
The TypeScript integration ensures you get:
All CMS-related code is centralized in one location
Update the integration by modifying a single file
Standardized approach to accessing CMS features across your application
No need to manage multiple imports or dependencies
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.
Make sure you have a working Svelte project set up with TypeScript support
You'll need your API token and project ID from your JustCMS dashboard
Follow these simple steps to install and configure JustCMS in your Svelte project:
Copy justCms.ts into your project's src/lib directory
Create a .env file to store your JustCMS credentials
Ensure your project is properly configured for TypeScript
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.
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>
Make sure your .env file is in the root directory and properly formatted
Verify that your tsconfig.json includes the necessary compiler options
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.
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.
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.
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:
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>
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>
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}
JustCMS functions can be easily integrated into any Svelte component
All API calls are asynchronous and should be handled with async/await
Full type safety for all API responses and parameters
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.
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.
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
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.
filters, start, and offset for customizing your page queries
Filter pages by specific category using the category slug
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
});
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
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.
All functions include TypeScript definitions for better development experience
Remember to implement try/catch blocks for error handling
Consider implementing loading indicators while data is being fetched
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.
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
}
Retrieves the large variant of an image (second variant in the array)
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);
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
}
isBlockHasStyle performs case-insensitive comparison
Direct access to commonly used image variants
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.
Always check if objects exist before using utility functions
Utility functions maintain TypeScript type safety
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.