Skip to content

How to generate SEO meta data with AI in Strapi

Learn step‑by‑step how to use an LLM to auto‑populate title tags, meta descriptions and keywords for Strapi content, with secure handling and audit trails.

By the Revisionary team · · 4 min read

turned on monitoring screen
Photo by Stephen Dawson on Unsplash

Generating SEO‑friendly meta data for every piece of content can be tedious, especially when a large headless CMS powers many pages. You can automate the process by calling an LLM from a Strapi lifecycle hook: the hook creates a title tag, description and keyword list, stores them in the entry, and lets Revisionary keep a versioned record of the generated values.

Why automate meta data with AI?

  • Consistency – The same prompt and model produce uniform phrasing across articles, products or blog posts.
  • Speed – New entries are enriched instantly, reducing manual copy‑editing workload.
  • Auditability – When Revisionary is enabled, every auto‑generated change is stored as a version, so editors can review or revert it.

Prerequisites

RequirementDetails
Strapi 5Running with a database supported by Strapi (PostgreSQL, MySQL or SQLite).
Node.jsVersion 18‑24 as defined in the /docs/getting-started/requirements page.
LLM API keyAn OpenAI, Anthropic or Azure OpenAI key (any provider that offers a REST completion endpoint).
Revisionary (optional)Installed to keep a versioned history of generated fields – see the /docs/everyday-use/history guide.

1. Store the API key securely

Add the key to your environment file and reference it in config/plugins.ts so it is not hard‑coded.

js
// config/plugins.ts
module.exports = ({ env }) => ({
  // other plugins …
  "my‑ai": {
    config: {
      apiKey: env("LLM_API_KEY"),
      model: "gpt-4o-mini",
    },
  },
});

The configuration page /docs/reference/configuration explains how environment variables are loaded.

2. Create a reusable AI service

Place the service in src/services/seo-ai.js. It sends the content to the LLM and parses the response.

js
// src/services/seo-ai.js
const fetch = require("node-fetch");

/**
 * Generate SEO fields for a given entry.
 * @param {object} data - The entry payload (title, body, etc.).
 * @param {object} cfg  - Plugin config containing apiKey and model.
 * @returns {Promise<object>} {titleTag, metaDescription, keywords}
 */
async function generate(data, cfg) {
  const prompt = `Write a concise SEO title (max 60 characters), a meta description (max 160 characters) and three comma‑separated keywords for the following content.\n\nTitle: ${data.title}\n\nBody: ${data.body}\n\nReturn JSON with keys titleTag, metaDescription and keywords.`;

  const response = await fetch("https://api.openai.com/v1/chat/completions", {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
      Authorization: `Bearer ${cfg.apiKey}`,
    },
    body: JSON.stringify({
      model: cfg.model,
      messages: [{ role: "user", content: prompt }],
      temperature: 0.2,
    }),
  });

  if (!response.ok) {
    const err = await response.text();
    throw new Error(`LLM request failed: ${err}`);
  }

  const { choices } = await response.json();
  const content = choices[0].message.content;
  // The LLM should return a JSON block – try to parse it safely.
  try {
    return JSON.parse(content);
  } catch {
    // Fallback: return empty strings so the entry still saves.
    return { titleTag: "", metaDescription: "", keywords: "" };
  }
}

module.exports = { generate };

The service is deliberately small; you can replace the endpoint or model without touching the lifecycle code.

3. Hook into the content type lifecycle

Add a beforeCreate and beforeUpdate hook to the content type that needs SEO enrichment, for example article.

js
// src/api/article/content-types/article/lifecycles.js
const { generate } = require("../../../services/seo-ai");

module.exports = {
  async beforeCreate(event) {
    const { data } = event.params;
    // Only call the AI if the fields are missing or empty.
    if (!data.seoTitle || !data.seoDescription) {
      const cfg = strapi.config.get("my‑ai");
      try {
        const seo = await generate(data, cfg);
        data.seoTitle = seo.titleTag || data.title;
        data.seoDescription = seo.metaDescription || "";
        data.seoKeywords = seo.keywords || "";
      } catch (e) {
        strapi.log.warn("AI SEO generation failed: " + e.message);
        // Proceed without AI data – editors can fill it later.
      }
    }
  },
  async beforeUpdate(event) {
    const { data, where } = event.params;
    // Regenerate only when the main content changes.
    if (data.title || data.body) {
      const cfg = strapi.config.get("my‑ai");
      try {
        const seo = await generate({ title: data.title, body: data.body }, cfg);
        data.seoTitle = seo.titleTag;
        data.seoDescription = seo.metaDescription;
        data.seoKeywords = seo.keywords;
      } catch (e) {
        strapi.log.warn("AI SEO generation failed on update: " + e.message);
      }
    }
  },
};

The lifecycle file lives next to the content‑type definition, as described in the Strapi documentation. When an entry is created or updated, the LLM runs, and the generated fields are saved alongside the rest of the entry.

4. Expose the fields through the Content API

If your frontend pulls SEO data via the public API, make sure the fields are part of the response schema. Edit the schema.json of the content type to add seoTitle, seoDescription and seoKeywords to the attributes section. Then, the API will return them automatically – see the /docs/reference/content-api page for details.

An orange neon sign reading AI on a dark grey textured circuit board
Photo by Igor Omilaev on Unsplash

5. Secure the integration

  • Rate limiting – Wrap the service call in a simple counter or use a library like express-rate-limit to avoid exceeding provider quotas.
  • Error handling – The lifecycle already logs a warning and lets the entry save without AI data, preventing a failed request from blocking editors.
  • Mask the key – Never expose the LLM key in the front‑end; keep it only in server‑side config.

When Revisionary is installed, every change created by the AI appears as a separate version. Editors can open the Version history panel on the right side of the Content Manager – see /docs/everyday-use/panel. The panel shows which fields were auto‑filled, making it easy to:

  1. Verify the relevance of the generated title or description.
  2. Revert to a previous version if the AI produced low‑quality copy.
  3. Add a custom note or tag the version (e.g., “AI‑generated meta”).

Because Revisionary stores field‑level diffs, you can also filter the audit log for changes to seoTitle or seoDescription – see the /docs/everyday-use/history guide for searching past versions.

7. Testing the workflow

  1. Create a draft article in the Strapi admin UI without filling the SEO fields.
  2. Save – the lifecycle hook triggers, the LLM returns JSON, and the fields populate automatically.
  3. Open the Version history panel to see the auto‑generated version.
  4. Publish the article and verify that the public Content API returns the new SEO data.
  5. Simulate a failure by removing the API key; the hook should log a warning and let the article save with empty SEO fields.

8. Common pitfalls and how to avoid them

SymptomCauseFix
Empty seoTitle after savePrompt not understood by the model → no JSON returned.Add explicit “return JSON only” instructions; test the prompt in the provider’s playground first.
Rate‑limit errors from providerToo many concurrent saves.Implement a queue or debounce rapid saves; increase the provider quota if needed.
API key leaked in logsconsole.log of the full request object.Never log cfg.apiKey; mask it if you need to debug request headers.
Revisionary does not show a versionThe content type is not enabled for versioning.Enable it under Revisionary → Settings → Content types – see /docs/getting-started/content-types.

9. Extending the pattern

  • Image alt‑text – Create a similar service that receives an image URL and returns a concise alt description.
  • Open Graph tags – Extend the prompt to include ogTitle, ogDescription and ogImage fields.
  • Multi‑language – Call the LLM once per locale, or use a translation model to generate localized meta data.

Conclusion

Automating SEO meta data with an LLM inside Strapi removes repetitive copy work, improves consistency, and—when paired with Revisionary—provides a full audit trail that lets editors keep control. By adding a secure service, wiring lifecycle hooks, and exposing the fields through the Content API, you get a production‑ready solution that scales with your content volume.


References

TagsAISEOStrapiLLMautomationcontent

The Revisionary team

Developers who build Revisionary, a version history plugin for Strapi 5. We write about Strapi, web development, AI and application security.

This article was written with the help of AI.

All articles