11ty

Integrate 11ty with Strapi to build fast, scalable static websites, combining 11ty’s efficient static site generation with Strapi’s powerful content management

11ty

What Is 11ty?

11ty (Eleventy) is a simple, powerful static site generator built on JavaScript. Unlike other generators like Gatsby, 11ty offers a minimalist, zero-config approach, allowing developers to create fast, efficient websites. It transforms templates, markdown files, and data into static HTML pages, resulting in incredibly fast-loading websites.

When integrated with Strapi, 11ty benefits from Strapi's robust content management system. 11ty supports multiple template languages, including Nunjucks, Liquid, and Handlebars, giving developers flexibility. Its focus on speed and simplicity makes 11ty ideal for projects of any size, providing power without complexity.

Why Integrate 11ty with Strapi

Integrating Strapi with 11ty creates a powerful Jamstack solution, combining both technologies' strengths to deliver fast, secure, and customizable websites. This integration is ideal for developers seeking complete control over content management and front-end performance. If you're new to Jamstack, its benefits include faster load times, enhanced security, and improved SEO.

Key Benefits

  • Faster Loading Times: 11ty pre-renders static HTML files to ensure near-instant page loads that improve user experience and SEO rankings.
  • Enhanced Security: Static sites have smaller attack surfaces, which can reduce vulnerabilities, especially with Strapi handling content management.
  • Improved SEO: Fast-loading, pre-rendered pages are favored by search engines, increasing site visibility.

Seamless Integration

  • Flexible Content Management: Strapi offers a user-friendly interface for managing content, while 11ty turns that content into static HTML.
  • API Options: Strapi supports both REST and GraphQL APIs, giving you flexible methods to fetch content for your 11ty templates.
  • Customization: Control both the back-end (Strapi) and front-end (11ty) to build tailored solutions.

Performance and Security

  • Pre-rendered Static HTML: Served directly from a CDN, static HTML ensures lightning-fast page loads and reduces server load.
  • Reduced Attack Surface: Static sites have fewer entry points for attackers, enhancing security.
  • Scalability: 11ty’s efficient builds and Strapi’s flexible content models handle growth smoothly.

How to Integrate 11ty with Strapi

Integrating 11ty with Strapi creates a powerful Jamstack solution that combines the flexibility of a static site generator with the content management capabilities of a headless CMS. This guide will walk you through the entire process, from initial setup to deployment. This tutorial will provide the necessary steps if you want to create a blog with 11ty and Strapi.

Prerequisites

Before starting, ensure you have the following installed:

  • Node.js (latest LTS version recommended)
  • npm or yarn package manager
  • Git (optional, but recommended for version control)

Setting Up Strapi

  1. Create a new directory for your project:
mkdir my-11ty-strapi-project
cd my-11ty-strapi-project
  1. Create a subdirectory for your Strapi back-end:
mkdir backend
cd backend
  1. Create a new Strapi project:
npx create-strapi@latest
  1. Follow the CLI prompts:
    • Choose your installation type (Quickstart or Custom)
    • Select your preferred database (SQLite is good for development)
  2. Once installed, start the Strapi server:
npm run develop
  1. Navigate to http://localhost:1337/admin to create your admin user and access the Strapi dashboard.
  2. Create a simple blog content model:
    • In the Strapi admin panel, navigate to "Content-Types Builder"
    • Click "Create new collection type"
    • Name it "Article"
    • Add fields: Title (Text), Content (Rich Text), Slug (Text), Published date (Date), Featured image (Media), Author (Relation to Users)
    • Save your collection type
    • Navigate to "Settings" > "Roles" > "Public" and give read permission to the Article collection
    • Create a few sample articles to test with

Setting Up 11ty

  1. Go back to your project root directory:
cd ..
mkdir frontend
cd frontend
  1. Initialize a new npm project and install 11ty:
npm init -y
npm install @11ty/eleventy
  1. Create a basic project structure:
mkdir _data
mkdir _includes
mkdir posts
  1. Create a basic configuration file, eleventy.js, in the root of your front-end directory:
module.exports = function(eleventyConfig) {
  return {
    dir: {
      input: ".",
      output: "_site",
      includes: "_includes",
      data: "_data"
    }
  };
};

Connecting 11ty to Strapi's API

  1. Install the node-fetch package to make API requests:
npm install node-fetch
  1. Create a JavaScript file in the _data directory to fetch data from Strapi. Name it articles.js:
const fetch = require('node-fetch');

module.exports = async function() {
  try {
    const response = await fetch('http://localhost:1337/api/articles?populate=*');
    const data = await response.json();
    return data.data;
  } catch (error) {
    console.error('Error fetching articles:', error);
    return [];
  }
};
  1. Create a base layout in _includes/base.njk:
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>{{ title }}</title>
  <link rel="stylesheet" href="/css/style.css">
</head>
<body>
  <header>
    <h1>My 11ty Blog with Strapi</h1>
    <nav>
      <a href="/">Home</a>
    </nav>
  </header>
  <main>
    {{ content | safe }}
  </main>
  <footer>
    <p>&copy; {{ new Date().getFullYear() }} My Blog</p>
  </footer>
</body>
</html>
  1. Create an index page index.njk in the root of your front-end directory:
---
layout: base.njk
title: My 11ty Blog with Strapi
---

<h1>Recent Articles</h1>

<ul class="articles-list">
{% for article in articles %}
  <li class="article-item">
    <h2><a href="/posts/{{ article.slug }}">{{ article.title }}</a></h2>
    <p>{{ article.publishedAt | date: "%Y-%m-%d" }}</p>
  </li>
{% endfor %}
</ul>
  1. Create a template for individual articles in posts/posts.njk:
---
layout: base.njk
pagination:
  data: articles
  size: 1
  alias: article
permalink: "posts/{{ article.slug }}/"
---

<article>
  <h1>{{ article.title }}</h1>
  <p>Published: {{ article.publishedAt | date: "%Y-%m-%d" }}</p>

  <div class="article-content">
    {{ article.content | safe }}
  </div>
</article>

Building and Testing Locally

  1. In the front-end directory, run:
npx @11ty/eleventy --serve
  1. This will build your site and start a local development server, typically at http://localhost:8080.
  2. Make sure your Strapi server is still running (in a separate terminal):
cd ../backend
npm run develop
  1. Visit http://localhost:8080 in your browser to see your blog with content from Strapi.

Preparing for Deployment

  1. Create a .env file in your front-end directory:
STRAPI_API_URL=http://localhost:1337
  1. Install the dotenv package:
npm install dotenv
  1. Update your articles.js data file to use the environment variable:
require('dotenv').config();
const fetch = require('node-fetch');

const API_URL = process.env.STRAPI_API_URL || 'http://localhost:1337';

module.exports = async function() {
  try {
    const response = await fetch(`${API_URL}/api/articles?populate=*`);
    const data = await response.json();
    return data.data;
  } catch (error) {
    console.error('Error fetching articles:', error);
    return [];
  }
};
  1. Add build scripts to your front-end package.json:
"scripts": {
  "dev": "eleventy --serve",
  "build": "eleventy"
}

Deployment Options

There are several ways to deploy your 11ty and Strapi application:

  1. Deploying Strapi on a VPS or PaaS
    • Set up a VPS (like DigitalOcean, Linode) or use a PaaS (like Heroku, Render)
    • Follow Strapi's deployment guides for your chosen platform
    • Set up environment variables for production database, etc.
  2. Deploying 11ty on Netlify
    • Push your front-end code to a GitHub repository
    • Sign up for Netlify and connect your repository
    • Configure the build settings:
      • Build command: npm run build
      • Publish directory: _site
    • Add environment variables in Netlify's dashboard:
  3. Deploying Both with Docker
    • Create a docker-compose.yml file in your project root
    • Create Dockerfiles for both front-end and back-end
    • Use Docker Compose to manage your multi-container application

Following this guide on integrating 11ty with Strapi can help you build a fully functional blog or website powered by 11ty and Strapi, ready for deployment. This setup gives you the benefits of a static site (speed, security) with the convenience of a content management system. For a more detailed walkthrough on how to create a blog with 11ty and Strapi, you can refer to our dedicated tutorial.

We invite you to explore our resources to take your 11ty and Strapi project further. You can deploy Strapi now or join our community for support and insights.

To demonstrate the power of integrating 11ty with Strapi, let’s explore a real-world example: a photo gallery app built using Strapi and 11ty. This project illustrates how combining these technologies creates a visually appealing, fast, and functional web application.

Project Overview

The photo gallery app utilizes the following key components:

  • Strapi: Handles content management and API creation
  • 11ty: Generates static HTML from templates and data
  • Tailwind CSS: Provides a responsive styling framework
  • Cloudinary: Manages image storage and optimization

This combination ensures a performant, scalable, and easily maintainable photo

gallery website.

Implementation Highlights

  1. Content Modeling in Strapi: Strapi creates a custom content type for photo galleries with fields for title, description, and image uploads.
  2. API Integration: 11ty fetches data from Strapi’s API endpoints to dynamically generate content at build time.
  3. Static Site Generation: 11ty generates static HTML pages for each gallery and photo, optimizing page load times and SEO.
  4. Image Optimization: Cloudinary handles image optimization for faster web delivery.
  5. Responsive Design: Tailwind CSS ensures the photo gallery is responsive across various devices and screen sizes.

Benefits Realized

  • Performance: The static site generates extremely fast load times.
  • Scalability: New galleries and photos can be added easily without affecting performance.
  • Content Management: Strapi’s user-friendly interface allows non-technical users to manage content easily.
  • Developer Experience: The separation of content management (Strapi) and presentation (11ty) streamlines the development process..

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 11ty documentation.

Frequently Asked Questions

11ty (Eleventy) is a static site generator that compiles content and templates into fast-loading static HTML files. When integrated with Strapi, 11ty fetches dynamic content through Strapi's REST or GraphQL APIs and pre-renders it into static pages. This provides the performance benefits of static sites with the flexibility of dynamic content management.

Integrating 11ty with Strapi combines the best of both worlds: 11ty’s fast, static page generation with Strapi’s flexible content management. This setup improves SEO, load times, and scalability while providing a simple interface for content creators and a powerful backend for developers.

You can fetch content from Strapi by using node-fetch to make HTTP requests to the Strapi API. Then, use this data to generate static pages with 11ty’s templating engine. For example, create a data file in 11ty that fetches Strapi data and then loops through it in a template.

GraphQL offers more precise data fetching compared to REST, reducing over-fetching and under-fetching. When using GraphQL with Strapi, you can customize your queries to fetch exactly the data you need, which is especially useful for more complex content models or dynamic content filtering.

Strapi’s media library handles uploads, and you can fetch media URLs through Strapi’s APIs. For optimized delivery, use services like Cloudinary or an external CDN to manage and serve media. 11ty’s image component allows you to use Strapi’s URLs and optimize images during build time.

You can use Strapi webhooks to automatically trigger 11ty rebuilds when content is created or updated. By integrating tools like Netlify or GitHub Actions, you can set up continuous deployment pipelines that rebuild and redeploy your site when content changes in Strapi.

Yes, you can deploy both Strapi and 11ty to Netlify. Strapi will need to be deployed on a Node.js-compatible platform like Heroku or DigitalOcean, while 11ty can be deployed directly to Netlify as a static site. Set up webhooks to trigger 11ty builds when content is updated in Strapi.

Ensure that you use HTTPS for secure communication between Strapi and 11ty, manage API keys securely using environment variables, and configure proper role-based access control (RBAC) in Strapi. If using authentication, ensure that JWT tokens are used securely in API requests.

11ty’s static site generation is SEO-friendly, and you can use dynamic meta tags and schema markup by integrating Strapi’s SEO fields into your templates. Strapi allows content editors to manage SEO metadata for each piece of content, ensuring that your pages are optimized for search engines.

You can use 11ty’s dynamic routing system to create individual pages based on Strapi’s content, like blog posts or product pages. Configure 11ty to generate dynamic routes for each piece of content fetched from Strapi, using parameters like slugs or IDs to build the URLs.