Skip to content

Get started with Next.js

In this guide you will build a small blog with Next.js (App Router) that reads its posts from Content Island:

  • A home page that lists every post.
  • A detail page per post, at /posts/<slug>, that renders its Markdown content.

Along the way you will see the basics you need in any Next.js project: Server Components, how to keep the access token on the server, caching with 'use cache' and Server Actions.

Prerequisites

Prepare your content in Content Island

  1. Create a new project from the Projects page.

  2. In the Model tab, create a model called post with these fields:

    Field nameTypeNotes
    titleShort TextRequired.
    slugShort TextRequired and unique.
    contentLong TextMarkdown body of the post.
  3. In the Content tab, add two or three posts and publish them.

  4. In the General tab, copy the project’s Token (the API access token).

Create the Next.js project

  1. Create a new project. Accept the defaults (TypeScript and App Router):

    Terminal window
    npx create-next-app@latest my-blog
    cd my-blog
  2. Install the Content Island client, marked (to render Markdown) and server-only:

    Terminal window
    npm install @content-island/api-client marked server-only

Configure the access token

The access token gives access to your project, so it must never reach the browser. Store it in .env.local, which Next.js loads automatically:

.env.local
CONTENT_ISLAND_ACCESS_TOKEN=your-access-token

Create the client

Create the client once and reuse it everywhere. The server-only import makes the build fail if a Client Component ever imports this file, so the token can’t leak by accident:

lib/content-island.ts
import 'server-only';
import { createClient } from '@content-island/api-client';
export const client = createClient({
accessToken: process.env.CONTENT_ISLAND_ACCESS_TOKEN!,
});

And a type that mirrors the post model:

lib/models.ts
export interface Post {
id: string;
title: string;
slug: string;
content: string;
}

Read the content

Put your queries in one module. The 'use cache' directive caches what the function returns, so Next.js can prerender the pages that use it at build time, and cacheLife('minutes') regenerates them in the background at most once a minute:

lib/posts.ts
import { cacheLife } from 'next/cache';
import { client } from './content-island';
import type { Post } from './models';
export async function getPosts() {
'use cache';
cacheLife('minutes');
return client.getContentList<Post>({ contentType: 'post' });
}
export async function getPostBySlug(slug: string) {
'use cache';
cacheLife('minutes');
const [post] = await client.getContentList<Post>({ contentType: 'post', 'fields.slug': slug });
return post ?? null;
}

List the posts

In the App Router, every component is a Server Component by default: it runs on the server, can be async and can read secrets. Read the posts right inside the page:

app/page.tsx
import Link from 'next/link';
import { getPosts } from '@/lib/posts';
export default async function Home() {
const posts = await getPosts();
return (
<main>
<h1>My blog</h1>
<ul>
{posts.map(post => (
<li key={post.id}>
<Link href={`/posts/${post.slug}`}>{post.title}</Link>
</li>
))}
</ul>
</main>
);
}

Run npm run dev and open http://localhost:3000 to see your posts.

Show a post

Create a dynamic route. generateStaticParams tells Next.js which slugs to prerender at build time, and notFound() renders the 404 page when a slug doesn’t exist:

app/posts/[slug]/page.tsx
import { notFound } from 'next/navigation';
import { marked } from 'marked';
import { getPostBySlug, getPosts } from '@/lib/posts';
interface Props {
params: Promise<{ slug: string }>;
}
export async function generateStaticParams() {
const posts = await getPosts();
return posts.map(post => ({ slug: post.slug }));
}
export default async function PostPage({ params }: Props) {
const { slug } = await params;
const post = await getPostBySlug(slug);
if (!post) {
notFound();
}
const html = await marked.parse(post.content);
return (
<main>
<h1>{post.title}</h1>
<article dangerouslySetInnerHTML={{ __html: html }} />
</main>
);
}

Server basics in Next.js

Server and Client Components

Server Component (default)Client Component ('use client')
Where does it run?On the server.In the browser (and once on the server to generate HTML).
Can it be async?Yes.No.
Can it use the token?Yes.No.
State and eventsNo.Yes (useState, onClick…).

Rule of thumb: read content in Server Components and pass the data as props to Client Components when you need interactivity.

Cached or always fresh

Thanks to 'use cache', the pages above are prerendered at build time and regenerated in the background when their cache expires. Choose how long with the cacheLife profile: 'seconds', 'minutes', 'hours', 'days', 'weeks' or 'max'.

If some content must be read on every request, don’t cache it: read it in a component wrapped in <Suspense>. Next.js prerenders the rest of the page and streams that part when the request arrives:

// app/page.tsx (always fresh version)
import { Suspense } from 'react';
import { client } from '@/lib/content-island';
import type { Post } from '@/lib/models';
async function PostList() {
const posts = await client.getContentList<Post>({ contentType: 'post' });
return (
<ul>
{posts.map(post => (
<li key={post.id}>{post.title}</li>
))}
</ul>
);
}
export default function Home() {
return (
<main>
<h1>My blog</h1>
<Suspense fallback={<p>Loading…</p>}>
<PostList />
</Suspense>
</main>
);
}

Server Actions: server functions you can call from the browser

Sometimes the browser needs data after the page has loaded (a “Load more” button, a search box…). A Client Component cannot use the client directly, because that would expose your token. A Server Action is a function marked with 'use server' that runs on the server and can be called from the browser as if it were local:

app/actions.ts
'use server';
import { client } from '@/lib/content-island';
import type { Post } from '@/lib/models';
const PAGE_SIZE = 5;
export async function loadMorePosts(page: number) {
return client.getContentList<Post>({
contentType: 'post',
pagination: { take: PAGE_SIZE, skip: page * PAGE_SIZE },
});
}
app/load-more.tsx
'use client';
import { useState } from 'react';
import { loadMorePosts } from './actions';
import type { Post } from '@/lib/models';
export function LoadMore() {
const [posts, setPosts] = useState<Post[]>([]);
const [page, setPage] = useState(0);
const handleClick = async () => {
const nextPosts = await loadMorePosts(page);
setPosts([...posts, ...nextPosts]);
setPage(page + 1);
};
return (
<>
<ul>
{posts.map(post => (
<li key={post.id}>{post.title}</li>
))}
</ul>
<button onClick={handleClick}>Load more</button>
</>
);
}

Render <LoadMore /> wherever you want the button, for example under the list in app/page.tsx.

Preview unpublished content

While you develop, prefix the token with PREVIEW_ to also read content that is not published yet:

.env.local
CONTENT_ISLAND_ACCESS_TOKEN=PREVIEW_your-access-token

See Preview Token for more details.

Next steps