VitePress

Integrate VitePress with Strapi to build fast, SEO-friendly static websites, combining VitePress’s optimized site generation with Strapi’s flexible content management

VitePress

What Is VitePress?

VitePress is a static site generator built on Vite optimized for speed and performance. It offers a seamless developer experience with features like hot module replacement (HMR) and automatic page preloading. VitePress is well-suited for documentation sites, with simple configuration and easy Vue.js integration.

Thanks to Vite's fast build system, VitePress provides quick build times and efficient rendering. Its minimalist design ensures easy customization, making it ideal for developers who need fast, SEO-friendly documentation and static websites.

Why Integrate VitePress with Strapi

Integrating VitePress with Strapi combines the strengths of both platforms. This combination offers developers a powerful solution for fast, dynamic, content-driven websites.

Key Benefits

  • Fast, Content-Rich Websites: Strapi’s content management and VitePress’s static site generation deliver high-performance, content-rich sites without compromising speed.
  • Separation of Concerns: Content editors manage content in Strapi, while developers focus on frontend development with VitePress. This separation streamlines workflows, allowing both teams to work independently.

Strapi’s Headless CMS Features

  • Customizable Content: Create custom content types, manage roles, and control access.
  • API-First Approach: Exposes content through REST or GraphQL endpoints for easy integration with VitePress.

Developer Experience

  • Vue-Based Development: VitePress offers a Vue-powered environment with hot module replacement and TypeScript support.
  • Flexible Content Retrieval: VitePress fetches content from Strapi’s REST or GraphQL API during build time. For real-time updates, implement client-side fetching.
  • Extensibility: Strapi’s robust plugin system extends functionality, while VitePress supports Vue components in Markdown for enhanced UI.

Performance & SEO

  • Fast Load Times: VitePress’s static output ensures quick load times and strong SEO.
  • Scalable Integration: As your project grows, this integration scales easily, allowing you to add new features without performance issues.

This modular approach provides a solid foundation for modern, content-driven websites, from blogs to comprehensive documentation sites.

How to Integrate and Deploy VitePress with Strapi

Integrating VitePress with Strapi creates a powerful stack, combining dynamic content management with fast static site generation. Here’s how to set up and deploy these technologies for production.

1. Set Up the Development Environment

Create separate directories for the VitePress frontend and Strapi backend:

project-root/
├── frontend/             # VitePress application
│   ├── docs/
│   ├── .vitepress/
│   └── package.json
├── backend/              # Strapi application
│   ├── src/
│   ├── config/
│   └── package.json
└── README.md

Initialize VitePress in the frontend directory:

npm init vitepress

Set up Strapi in the backend directory:

npx create-strapi-app@latest .

2. Configure API Endpoints

Create necessary content types and API endpoints through the Strapi admin panel.

Then set up an API client in your VitePress project:

// .vitepress/api/strapi.js
import axios from 'axios'

const apiURL = import.meta.env.VITE_API_URL || 'http://localhost:1337/api'

const api = axios.create({
  baseURL: apiURL,
  headers: {
    'Content-Type': 'application/json'
  }
})

export default api
  1. Use Data Fetching Strategies

Create modular fetch functions for different content types:

// .vitepress/api/articles.js
import api from './strapi'

export const getArticles = async (params = {}) => {
  try {
    const response = await api.get('/articles', { params })
    return response.data
  } catch (error) {
    console.error('Error fetching articles:', error)
    return { data: [] }
  }
}

4. Implement Dynamic Route Generation

Generate routes based on your Strapi content:

// .vitepress/config.js
import { defineConfig } from 'vitepress'
import { getArticles } from './api/articles'

5. Adopt Deployment Best Practices

Use environment variables for API URLs, but do not expose sensitive tokens in client-accessible variables like VITE_API_TOKEN. Store and use tokens securely on the server side.

Implement proper caching strategies:

// .vitepress/api/cache.js
const cache = new Map()

export const getCachedData = async (key, fetchFn, ttl = 60000) => {
  const cachedItem = cache.get(key)
  
  if (cachedItem && Date.now() - cachedItem.timestamp < ttl) {
    return cachedItem.data
  }
  
  const data = await fetchFn()
  
  cache.set(key, {
    data,
    timestamp: Date.now()
  })
  
  return data
}

Configure CORS in Strapi for production by exporting an array with the 'strapi::cors' middleware in 'config/middlewares.js', like this:

module.exports = [
  // ...other middlewares
  {
    name: 'strapi::cors',
    config: {
      origin: ['https://your-vitepress-site.com'],
      headers: ['Content-Type', 'Authorization', 'Origin'],
      methods: ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS'],
    },
  },
];

Set up a webhook in Strapi to trigger VitePress rebuilds:

// Strapi webhook configuration
{
  "name": "Trigger VitePress rebuild",
  "url": "https://api.netlify.com/build_hooks/your-build-hook-id",
  "headers": {
    "Content-Type": "application/json"
  },
  "events": [
    "entry.create",
    "entry.update",
    "entry.delete"
  ]
}

The configuration of webhooks in Strapi lets you automate your static site generation process. This approach is similar to static site generation with Strapi, where changes in content trigger site rebuilds.

Optimize Strapi queries for performance:

const getOptimizedArticles = async () => {
  const response = await api.get('/articles', {
    params: {
      fields: ['title', 'slug', 'publishedAt'],
      populate: {
        featuredImage: {
          fields: ['url', 'alternativeText']
        }
      },
      pagination: {
        page: 1,
        pageSize: 10
      },
      sort: ['publishedAt:desc']
    }
  })
  return response.data
}

These steps will help you create a robust integration between VitePress and Strapi that is ready for production. This setup gives you dynamic content management with the speed benefits of static sites.

We recommend updating both platforms, implementing proper error handling, and monitoring your deployment. This will give you a flexible, scalable solution for content-driven websites that can grow with your needs.

Project Example (+ GitHub Project Repo)

Let's walk through a real-world example of how integrating VitePress with Strapi works.

Project Architecture

The architecture follows a clean separation of concerns:

  • Strapi Backend: Handles content creation and storage.
  • VitePress Frontend: Generates static pages based on Strapi content.
  • API Layer: Connects Strapi with VitePress.

This setup allows content editors to work within Strapi while developers focus on frontend development with VitePress.

Key Integration Points

There are three core elements that drive the integration:

  1. Content Fetching: VitePress fetches data from Strapi’s API during the build process.
  2. Dynamic Route Generation: VitePress generates routes based on Strapi content.
  3. Markdown Rendering: Strapi’s content is converted to Markdown for VitePress to process.

Code Walkthrough

Let's examine key code snippets from a sample GitHub project showing Strapi integration (note: this example uses React, but the concepts apply to VitePress):

For API configuration:

// api.js
import axios from 'axios';

const api = axios.create({
  baseURL: 'http://localhost:1337/api',
});

export const fetchArticles = async () => {
  try {
    const response = await api.get('/articles');
    return response.data;
  } catch (error) {
    console.error('Error fetching articles:', error);
    return [];
  }
};

This creates a reusable API client for fetching Strapi data. You can use this during the build process in VitePress.

For dynamic route generation, VitePress relies on its file-based routing system and does not support an asynchronous 'buildEnd' hook for injecting routes. Instead, generate route files or use available plugins and build-time scripts to create content dynamically.

For content rendering, create a Vue component:

<!-- ArticleContent.vue -->
<script setup>
import { ref, onMounted } from 'vue'
import { fetchArticles } from '../api'

const articles = ref([])

onMounted(async () => {
  const response = await fetchArticles()
  articles.value = response.data
})
</script>

<template>
  <div>
    <article v-for="article in articles" :key="article.id">
      <h2>{{ article.attributes.title }}</h2>
      <div v-html="article.attributes.content"></div>
    </article>
  </div>
</template>

You can use this component within VitePress Markdown files:

# Our Blog

Here are our latest articles:

<ArticleContent />

This setup combines the best of both worlds—content management through Strapi and static site generation through VitePress. Content editors manage content in Strapi's interface, while developers benefit from VitePress for high-performance, static site generation.

Strapi Open Office Hours

If you have any questions about Strapi 5 or just would like to stop by and say hi, you can join us at Strapi's Discord Open Office Hours, Monday through Friday, from 12:30 pm to 1:30 pm CST: Strapi Discord Open Office Hours.

For more details, visit the Strapi documentation and the Vitepress documentation.

Frequently Asked Questions

VitePress is a static site generator built on Vite optimized for speed and performance. It offers a seamless developer experience with features like hot module replacement (HMR) and automatic page preloading, making it ideal for documentation sites and static websites.

Integrating Strapi with VitePress combines Strapi's robust content management system with VitePress's speed and static site generation. This allows developers to deliver fast, content-driven websites with excellent SEO performance, scalability, and a seamless editorial workflow.

  • Fast, Content-Rich Websites: VitePress generates fast-loading static sites, while Strapi provides powerful content management.
  • Separation of Concerns: Content is managed in Strapi while the frontend is developed using VitePress, allowing for efficient workflows.
  • Enhanced Performance: Static HTML generation improves load times and SEO.
  • Flexible Content Management: Strapi's customizable content models can be easily consumed by VitePress, enhancing flexibility.
  1. Create a new Strapi project and configure your content types.
  2. Enable public API permissions for content access.
  3. Use Strapi's REST or GraphQL APIs to fetch content in your VitePress project.
  4. Ensure proper CORS configuration to allow communication between Strapi and VitePress.

You can use the axios library in your VitePress project to fetch content from Strapi's REST API. Create a strapi.js client to manage your API calls and use it within your VitePress pages to fetch and display content.

Yes, you can integrate GraphQL with Strapi in VitePress. Enable the GraphQL plugin in Strapi, then use a GraphQL client like Apollo or Urql in VitePress to make queries and retrieve content.

To deploy, push your VitePress frontend to platforms like Vercel or Netlify. For Strapi, you can deploy to any Node.js-compatible platform such as Heroku, DigitalOcean, or AWS. Use webhooks to trigger a rebuild of your VitePress site whenever content changes in Strapi.

You can fetch dynamic content from Strapi using API calls (either REST or GraphQL). For example, you can fetch blog posts or product information during the build process in VitePress. For real-time content, you can use client-side fetching for dynamic pages.

  • Use caching strategies to reduce the number of API calls to Strapi.
  • Ensure proper pagination and filtering when fetching large datasets.
  • Optimize images in Strapi before rendering them in VitePress.
  • Implement proper error handling and fallbacks when fetching content from Strapi.

Yes, VitePress can integrate with other headless CMS platforms that offer an API, such as Contentful, Sanity, or WordPress. However, Strapi's open-source nature and flexibility make it a popular choice for many VitePress projects.