Astro Integration Guide

A simple guide to connecting your Astro project with JustCMS

Installation and Setup Guide for JustCMS with Astro

Setting up JustCMS with your Astro project is a straightforward process that requires just a few simple steps. Let's walk through the essential setup requirements to get you started quickly.

Step-by-Step Installation Process

Add Client File

Place the justcms.ts file in your project's src/lib directory

Configure Environment Variables

Set up your API token and project ID in the .env file

TypeScript Setup

Ensure TypeScript support is properly configured in your Astro project

1. Adding the Client File

Start by adding the JustCMS client file to your project structure:

  1. Create a lib directory inside your src folder if it doesn't exist already
  2. Place the justcms.ts file into src/lib/

2. Environment Variables Setup

You'll need to set up environment variables to configure your JustCMS connection. Create or modify your .env file in the project root directory with the following variables:

PUBLIC_JUSTCMS_TOKEN=your_justcms_api_token
PUBLIC_JUSTCMS_PROJECT=your_justcms_project_id

Make sure to replace the values with your actual JustCMS API token and project ID. These credentials are essential for establishing a connection with your JustCMS content.

3. TypeScript Configuration

Your Astro project needs to be configured with TypeScript support. If you haven't set this up yet, refer to the official Astro documentation for TypeScript configuration guidance.

Verification

To verify your installation, you can try importing and using the client in any Astro component:

import { createJustCMSClient } from '../lib/justcms';

const justCMS = createJustCMSClient();
const categories = await justCMS.getCategories();

If everything is set up correctly, you should be able to fetch data from your JustCMS project without any errors.

Basic Usage and Configuration

Setting up JustCMS in your Astro project is straightforward. Once you have completed the installation steps, you can start using the client to fetch content from your JustCMS instance. Let's go through the basic usage and see how to implement a simple example.

Importing and Initializing the Client

To begin using JustCMS in your Astro components, you'll need to import the client and initialize it. The process is simple and requires just a couple of lines of code.

import { createJustCMSClient } from '../lib/justcms';

const justCMS = createJustCMSClient();

Import the client

Import createJustCMSClient from your local justcms.ts file

Initialize the client

Create a new instance using createJustCMSClient()

Ready to use

The client is now configured and ready to fetch data

Practical Example: Fetching Categories

Let's look at a complete example of how to fetch and display categories in an Astro component. This example demonstrates the basic pattern you'll use for most JustCMS operations.

---
import { createJustCMSClient } from '../lib/justcms';

const justCMS = createJustCMSClient();
const categories = await justCMS.getCategories();
---

<html>
  <body>
    <h2>Categories</h2>
    <ul>
      {categories.map((cat) => (
        <li key={cat.slug}>{cat.name}</li>
      ))}
    </ul>
  </body>
</html>

In this example, we're performing three main steps:

  • Importing the JustCMS client
  • Creating a client instance
  • Fetching categories using the getCategories() method

The data is then rendered in a simple list format, displaying the name of each category.

TypeScript Support

All responses are fully typed for better development experience

Async/Await

All API calls return promises and work with async/await syntax

Component Integration

Seamlessly integrates with Astro's component structure

This basic setup provides the foundation for more complex operations with JustCMS. You can use the same pattern to fetch pages, menus, and other content types, making it easy to build out your entire website using JustCMS as your content source.

Available API Functions

JustCMS provides several core API functions to fetch different types of content from your CMS. Let's explore each function and see how to use them in your Astro project.

Fetching Categories

The getCategories() function allows you to retrieve all categories from your JustCMS project. This is useful for building navigation menus or category filters.

const categories = await justCMS.getCategories();
// Returns: Category[]

Working with Pages

The getPages() function is a versatile method that fetches pages with optional filtering and pagination support. You can use it to retrieve specific sets of pages based on your requirements.

const pages = await justCMS.getPages({
  filters: { category: { slug: 'blog' } },
  start: 0,
  offset: 10,
});
// Returns: PagesResponse

filters

Apply filters to get specific pages (e.g., by category)

start

Starting point for pagination

offset

Number of items to fetch per page

Getting a Single Page

Use the getPageBySlug() function when you need to fetch a specific page using its slug. This is perfect for individual page views or detailed content displays.

const page = await justCMS.getPageBySlug('about-us');
// Returns: PageDetail

Fetching Menus

The getMenuById() function retrieves a menu structure by its ID. This is essential for building navigation components in your Astro site.

const menu = await justCMS.getMenuById('main-menu');
// Returns: Menu

Type-Safe Responses

All functions return fully typed responses for better development experience

Simple Integration

Easy to use with Astro's server-side rendering

Flexible Options

Customizable parameters for precise content fetching

These core functions provide everything you need to build a fully functional website with JustCMS and Astro. Each function is designed to be simple to use while offering the flexibility needed for various use cases.

Utility Functions in JustCMS

JustCMS provides several utility functions that make it easier to work with different content types in your Astro project. These helper functions handle common tasks when working with content blocks, images, and categories.

Content Block Style Checking

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

const isHighlighted = justCMS.isBlockHasStyle(block, 'highlight');
// Returns: boolean

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 simplify the process of working with image assets in your content:

// Get large image variant
const largeImage = justCMS.getLargeImageVariant(page.coverImage);

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

Category Checking

The hasCategory function provides an easy way to check if a page belongs to a specific category. This is particularly useful for filtering and conditional rendering based on content categories.

const isBlogPost = justCMS.hasCategory(page, 'blog');
// Returns: boolean

Key Benefits

These utility functions offer:

Type Safety

All functions are fully typed for TypeScript support

Simplified Workflow

Reduces common content handling tasks to single function calls

Consistent Behavior

Ensures uniform handling of content across your Astro project

By using these utility functions, you can streamline your content handling code and maintain a more consistent approach to working with JustCMS content in your Astro project. Each function is designed to handle a specific common use case, reducing the amount of repetitive code you need to write.