Learn how to integrate JustCMS with your Next.js project using our type-safe client
JustCMS Next.js Integration provides a seamless way to connect your Next.js applications with JustCMS content management system. This integration is designed to be simple yet powerful, offering a type-safe approach to fetch and manage your content.
Full type safety with comprehensive TypeScript definitions for all API responses
One unified client that handles all JustCMS API interactions
Easy access to categories, pages, and menus with built-in filtering and pagination
Quick setup using environment variables for API token and project ID
The integration is built around a single client that encapsulates all necessary functionality for interacting with JustCMS. This approach simplifies your codebase and makes it easier to maintain consistency across your application.
Setting up JustCMS in your Next.js project is straightforward and requires just a few key steps. Follow this guide to get started with the integration.
An existing or new Next.js project
Project must be configured for TypeScript
Valid API token and project ID from your JustCMS account
1. Create the Client File Directory
First, create a lib directory in your project root if it doesn't already exist. This will house the JustCMS client file:
mkdir lib
2. Add the Client File
Create a new file named justCms.ts in your lib directory and copy the JustCMS client code into it.
// lib/justCms.ts
touch lib/justCms.ts
3. Configure TypeScript
Ensure your tsconfig.json includes the necessary compiler options for the client:
{
"compilerOptions": {
"target": "es5",
"lib": ["dom", "dom.iterable", "esnext"],
"strict": true,
"esModuleInterop": true
},
"include": ["next-env.d.ts", "**/*.ts", "**/*.tsx"],
"exclude": ["node_modules"]
}
4. Set Up Environment Variables
Create a .env.local file in your project root to store your JustCMS credentials:
# .env.local
NEXT_PUBLIC_JUSTCMS_TOKEN=YOUR_JUSTCMS_API_TOKEN
NEXT_PUBLIC_JUSTCMS_PROJECT=YOUR_JUSTCMS_PROJECT_ID
To verify that everything is set up correctly, you can create a simple test component:
// pages/test.tsx
import { createJustCmsClient } from '../lib/justCms';
export default function TestPage() {
return <div>JustCMS Test Page</div>;
}
export async function getStaticProps() {
const justCms = createJustCmsClient(
process.env.NEXT_PUBLIC_JUSTCMS_TOKEN,
process.env.NEXT_PUBLIC_JUSTCMS_PROJECT
);
try {
const categories = await justCms.getCategories();
console.log('Successfully connected to JustCMS!');
return { props: {} };
} catch (error) {
console.error('Error connecting to JustCMS:', error);
return { props: {} };
}
}
Your JustCMS integration is now ready to use
Start fetching content using the available client functions
Refer to the documentation for usage examples and API details
With these steps completed, you can now start using JustCMS in your Next.js project. The client provides various functions for fetching categories, pages, and menus, which you can implement based on your project needs.
Configuring JustCMS in your Next.js project is straightforward and requires setting up a few environment variables. This guide will walk you through the essential configuration steps to get your integration up and running.
Create a .env.local file in your project's root directory. This file will store your JustCMS credentials and configuration settings. Next.js automatically loads these environment variables during development and production.
# .env.local
NEXT_PUBLIC_JUSTCMS_TOKEN=YOUR_JUSTCMS_API_TOKEN
NEXT_PUBLIC_JUSTCMS_PROJECT=YOUR_JUSTCMS_PROJECT_ID
Your unique API token for authentication with JustCMS services
The project ID that identifies your JustCMS project
After setting up your environment variables, you can use them in your application to initialize the JustCMS client. Here's how to access these variables in your code:
import { createJustCmsClient } from '../lib/justCms';
const justCms = createJustCmsClient(
process.env.NEXT_PUBLIC_JUSTCMS_TOKEN,
process.env.NEXT_PUBLIC_JUSTCMS_PROJECT
);
Never commit .env.local to version control
Create .env.example to document required variables
Double-check values match your JustCMS dashboard
Set variables in your hosting platform's environment settings
Important: Make sure to add .env.local to your .gitignore file to prevent accidentally exposing your credentials. For deployment, configure these environment variables in your hosting platform's settings panel.
Ensure exact matching of environment variable names
Confirm API token is copied correctly without extra spaces
Apply changes to environment variables by restarting Next.js
Let's explore some practical examples of how to use the JustCMS client in your Next.js project. These examples will show you common implementation patterns and data fetching approaches.
import { GetStaticProps } from 'next';
import { createJustCmsClient, Category } from '../lib/justCms';
interface CategoriesPageProps {
categories: Category[];
}
export default function CategoriesPage({ categories }: CategoriesPageProps) {
return (
<div>
<h2>Categories</h2>
<ul>
{categories.map((cat) => (
<li key={cat.slug}>{cat.name}</li>
))}
</ul>
</div>
);
}
export const getStaticProps: GetStaticProps = async () => {
const justCms = createJustCmsClient(yourToken, yourProjectId);
const categories = await justCms.getCategories();
return {
props: { categories },
revalidate: 60,
};
};
In this example, we create a page that fetches and displays all categories from your JustCMS project. The page uses Next.js's getStaticProps for static generation with incremental static regeneration set to 60 seconds.
import { GetStaticProps } from 'next';
import { createJustCmsClient } from '../lib/justCms';
export default function BlogPost({ page }) {
return (
<article>
<h1>{page.title}</h1>
<div>{page.content}</div>
</article>
);
}
export const getStaticProps: GetStaticProps = async ({ params }) => {
const justCms = createJustCmsClient(yourToken, yourProjectId);
const page = await justCms.getPageBySlug(params.slug);
return {
props: { page },
revalidate: 60,
};
};
Use getStaticProps for content that doesn't change frequently
Set revalidate period to update content periodically
Leverage TypeScript interfaces for better development experience
export default function Navigation() {
const [menu, setMenu] = useState(null);
useEffect(() => {
const justCms = createJustCmsClient(yourToken, yourProjectId);
async function fetchMenu() {
const menuData = await justCms.getMenuById('main-menu');
setMenu(menuData);
}
fetchMenu();
}, []);
if (!menu) return <div>Loading...</div>;
return (
<nav>
{menu.items.map((item) => (
<Link key={item.id} hrref={item.url}>
{item.label}
</Link>
))}
</nav>
);
}
These examples demonstrate the most common use cases for JustCMS in a Next.js application. Remember to always handle loading states and errors appropriately in your components. The client provides type-safe responses, making it easier to work with the returned data in a TypeScript environment.
Always implement proper error handling in your components
Show loading indicators while content is being fetched
Utilize Next.js built-in caching mechanisms for better performance
The JustCMS client provides several core functions to interact with your content. Each function is designed to handle specific data fetching needs while maintaining type safety.
This function retrieves all categories available in your JustCMS project. Categories are returned as an array of Category objects, each containing essential information like name and slug.
const categories = await justCms.getCategories();
// Returns: Category[]
The getPages function offers flexible options for fetching pages, including filtering by category and pagination support. You can customize the request using optional parameters.
Filter pages by category or other criteria
Control the number of pages returned using start and offset
All responses maintain TypeScript type definitions
// Get all pages
const allPages = await justCms.getPages();
// Get pages with filters
const filteredPages = await justCms.getPages({
filters: { category: { slug: 'blog' } }
});
// Get paginated pages
const paginatedPages = await justCms.getPages({
start: 0,
offset: 10
});
Use this function to retrieve comprehensive information about a specific page using its slug. You can optionally specify a version to fetch specific content versions.
const page = await justCms.getPageBySlug('about-us');
// Returns: PageDetail
// With version
const specificVersion = await justCms.getPageBySlug('about-us', 'v1');
This function fetches a complete menu structure including all menu items. It's particularly useful for building navigation components.
const menu = await justCms.getMenuById('main-menu');
// Returns: Menu
All functions return properly typed responses
Built-in error handling for failed requests
All functions return promises for async operations
Each function is designed to be intuitive and type-safe, making it easy to integrate JustCMS content into your Next.js application. Remember to handle potential errors and loading states in your components when using these functions.
JustCMS provides several utility functions that make it easier to work with content blocks, images, and categories. These helper functions streamline common operations and improve code readability in your Next.js application.
The isBlockHasStyle function allows you to check if a content block contains a specific style. This is particularly useful when you need to apply conditional rendering based on block styles.
const isHighlighted = justCms.isBlockHasStyle(block, 'highlight');
// Returns true if the block has 'highlight' style
Retrieves the large variant of an image (typically the second variant in the array)
Extracts the first image from an image block, simplifying image access
These image utilities make it straightforward to handle different image variants and access images within content blocks. Here's how you can use them:
// Get large image variant
const largeImage = justCms.getLargeImageVariant(page.coverImage);
// 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 particularly useful when filtering or organizing content.
const isBlogPost = justCms.hasCategory(page, 'blog');
// Returns true if the page belongs to the 'blog' category
These utility functions are designed to make your development experience smoother and more efficient when working with JustCMS content. They handle common use cases and reduce the amount of repetitive code you need to write.