跳到主要内容

Enable X (Twitter) Cards in Docusaurus

· 阅读需 3 分钟
liruqi
Founder of Chinapedia

To enable X (formerly Twitter) cards in Docusaurus, you primarily configure the metadata within your docusaurus.config.js (or .ts) file. Docusaurus uses these settings to populate the <head> tags that social media platforms crawl to generate preview cards. [1, 2, 3]

1. Global Configuration

Open your docusaurus.config.js and add or update the themeConfig object. This sets the default card behavior for your entire site. [2, 4, 5]

module.exports = {
// ... other config
themeConfig: {
metadata: [
{name: 'twitter:card', content: 'summary_large_image'},
{name: 'twitter:site', content: '@YourTwitterHandle'},
{name: 'twitter:creator', content: '@YourTwitterHandle'},
],
image: 'img/docusaurus-social-card.jpg', // Path to your default social card image
},
};

2. Individual Page Metadata

If you want a specific blog post or documentation page to have its own unique X card image, you can override the global settings using Front Matter at the top of your Markdown file. [1, 6]

---
title: My Awesome Page
description: A brief summary of this page for the X card.
image: /img/unique-page-card.png
---
# Your Content Here

3. Key Metadata Tags

Ensure these specific tags are present (either globally or per page) for the best results:

  • twitter:card: Set to summary (small image) or summary_large_image (full-width image).
  • twitter:image: The URL to the image. Docusaurus typically handles this via the image field in your config or front matter.
  • og:title & og:description: X often falls back to Open Graph (OG) tags if specific Twitter tags are missing. [7, 8]

4. Testing Your Card

After deploying your site, you can verify how the card looks using the X Post Validator (note: X has moved some validation features directly into the post composer preview, but third-party tools like OpenGraph.xyz are also excellent for testing). [9, 10, 11]

Would you like to know how to automate social card generation for every page instead of creating images manually?

[11]: https://www.tweetarchivist.com/twitter-card-validator-guide#:~:text=This%20process%20usually%20completes%20within%20a%20few,%28%20X%20%28formerly%20Twitter%29%20%27s%20feed.)