Menu

Backend API

Docsta is designed to work with any content source, but its default setup is API-ready. You can integrate your own backend services or connect to headless CMSs like Sanity, Strapi, or custom APIs. This section explains how to connect, fetch, and organize backend data efficiently.

1. Connecting to an API

If you're using a headless CMS or a custom REST/GraphQL API, you’ll typically fetch data from it using async functions in your lib/ or services/ folder.

Example: lib/api.ts

export async function fetchDocs() {
const res = await fetch(`${process.env.NEXT_PUBLIC_API_URL}/docs`)
if (!res.ok) throw new Error('Failed to fetch docs')
return res.json()
}

Use process.env for safe URL injection via environment variables.

2. Sanity Integration (Optional Default)

Docsta supports Sanity CMS out of the box. You can fetch content using the @sanity/client package.

Example: lib/sanity.ts

3. Structuring API Logic

You can organize your API logic in the following folders:

lib/
├── api.ts     # General REST/GraphQL fetchers
├── sanity.ts     # Sanity-specific content logic
└── mdx.ts    # MDX or local file readers

Use a single point of entry to keep your data sources modular and manageable.

import { createClient } from '@sanity/client'

export const sanityClient = createClient({
projectId: process.env.NEXT_PUBLIC_SANITY_PROJECT_ID!,
dataset: process.env.NEXT_PUBLIC_SANITY_DATASET!,
apiVersion: process.env.NEXT_PUBLIC_SANITY_API_VERSION!,
useCdn: true,
})

export async function fetchDocs() {
return await sanityClient.fetch(`*[_type == "doc"]{title, slug, content}`)
}
4. Using in Pages

Use these fetchers in your page.tsx or getStaticProps (if using Pages Router):

import { fetchDocs } from '@/lib/api'

export default async function DocsPage() {
const docs = await fetchDocs()

return (
<div className="prose dark:prose-invert">
<h1>Documentation</h1>
{docs.map(doc => (
<div key={doc.slug}>{doc.title}</div>
))}
</div>
)
}
5. Error Handling & Fallbacks

Always handle API errors gracefully to prevent build-time or runtime crashes:

try {
const data = await fetchDocs()
if (!data) return notFound()
return data
} catch (err) {
console.error('Error fetching docs:', err)
return []
}
6. Custom Endpoints (Optional)

If you need to expose your own API (e.g. for dynamic search or feedback), use the app/api or pages/api folder:

Example: /app/api/search/route.ts

export async function GET(req: Request) {
const query = new URL(req.url).searchParams.get('q')
const results = await searchDocs(query)
return Response.json(results)
}
7. Authentication (If Required)

For protected APIs, attach headers/tokens:

await fetch(`${API}/user`, {
headers: {
Authorization: `Bearer ${process.env.API_TOKEN}`,
  },
})

Store secure tokens in .env.local and never expose them on the client.

8. API Tools & Helpers

You can enhance your backend integration with:

  • 🛠 swr or react-query for client-side caching
  • 🔒 jsonwebtoken for auth
  • 📦 axios for advanced HTTP client features
  • 🌐 GraphQL clients like urql or Apollo

Docsta makes it easy to pull data from any backend—whether it's a CMS, REST API, or your own custom microservice.

👉 Next Up: Learn how to fetch and render this data using MDX, Sanity, or dynamic routing.

What did you think of this content?

like-icon

It was helpful

dislike-icon

It was not helpful

feedback-icon

I have a feedback