跪拜 Guibai
← Back to the summary

Build-Time Pre-Rendering Turns a Vue3 SPA into 21 Crawler-Friendly Pages

Vue3 + Vite Pure SPA SEO Engineering: Build-time Pre-rendering of 21 Pages

1. Background: A pure SPA is almost blank in search engines

At the end of last year, I took over a data API site that I had been maintaining. The front end is a standard Vue3 + Vite + vue-router (createWebHistory) setup. The backend is a REST API on a separate domain. Deployment is just dropping dist into nginx, with a pseudo-static rewrite of try_files $uri $uri/ /index.html.

After three months of being live, traffic was almost zero. After checking, three phenomena existed at the same time:

The problem is not Vue, nor the nginx configuration. The structural precondition of this architecture is: the whole world has only one HTML entry point. This article records the complete transformation plan and the pitfalls encountered. The final result is 21 static pages with independent TDK, independent body content, and independent structured data, all generated at build time with zero runtime cost.

First, let's clarify a term. Strictly speaking, this is called build-time pre-rendering, not "nginx pseudo-static" — pseudo-static is when the server rewrites /a to /a.php, making the URL pretty but the page is still dynamically generated. Here, we actually write out the HTML files at build time. The products are truly static files, and the server does not need any rewrite rules. In the Chinese SEO community, it's common to call the process of a dynamic site being staticized "pseudo-static," which is easily confused. This article should clarify it.

2. The Essence of the Problem: Three Layers of SPA Disconnection in Crawler Eyes

Layer 1: Single entry point. try_files routes all paths back to index.html, so /housing/, /market/, /api-docs/ are the same file at the HTTP level. Crawlers get the homepage's title, description, and canonical, which tells search engines "I only have one page here."

Layer 2: Body content relies on JS. The page body only appears after main.js executes, route matching, and API responses. Google can execute JS, but has a render budget. Once inner pages increase, the queue is measured in weeks. Baidu and Bing have weaker JS rendering capabilities, and AI crawlers (GPTBot, Bytespider, etc.) only fetch HTML.

Layer 3: Confusing URL semantics. Whether to include trailing slashes, legacy paths from the old site, and nonexistent paths all return 200, creating duplicate content and soft 404s.

Conclusion: Don't solve this at runtime. Crawlers want static HTML, so give them static HTML at build time.

3. Solution Selection

Solution Approach Conclusion
SSR / Nuxt rewrite Server-side render each route Introducing a Node service for a pure front-end project would double operational costs. Abandoned.
Headless browser pre-rendering Launch Puppeteer after build to capture DOM per page One browser instance per page, likely to timeout on CI; products need secondary processing. Abandoned.
Build-time template injection Directly read/write dist/index.html template, generate subdirectories per path Zero runtime dependencies, products are true static files, nginx outputs as-is. Adopted.

The core insight of the third approach: Vite's built dist/index.html is itself a template — resource references (<script src>, <link rel="stylesheet">) point to /assets/ hashed filenames, unrelated to specific pages. As long as you replace the common info in <head> and stuff the body into the mount point, the same template can derive any number of pages.

The whole flow: Read template → Strip common head tags → Write dedicated TDK → Inject JSON-LD → Pre-place body snapshot → Output to subdirectories → Generate sitemap.

4. Step-by-step Implementation

4.1 Create an SEO Configuration Hub

All page titles, descriptions, and body snapshots are maintained in one file. The build script only consumes it. Adding a page = adding a configuration entry, no need to touch build logic.

// src/seo/routes.js
export const SITE_ORIGIN = "https://example.com";
export const SEO = {
  "/": {
    title: "Acme Data API|一站式公开数据接口市场",
    description: "招投标、房产、行情、汇率等公开数据 REST 接口。",
    keywords: "数据API,公开数据接口",
    h1: "一站式公开数据接口",
  },
  "/bid/zhejiang": {
    title: "工程建设招投标数据接口|38 万+ 公告",
    description: "招投标公告与项目时间线,按项目编号串联。",
    keywords: "招投标数据,招标公告接口",
    h1: "工程建设招投标数据",
  },
  // ...每个需要被收录的路径一条
};
export const SNAPSHOT_PATHS = ["/bid/zhejiang", "/housing", "/market", "/api-docs"];
export const absUrl = (p) => SITE_ORIGIN + (p === "/" ? "/" : p + "/");

Note the trailing slash in absUrl. The third pitfall later is specifically about it.

4.2 Write a Vite Plugin to Generate Pages in writeBundle

The choice of hook is critical. Differences among three candidates:

// vite.config.js
function seoStaticPages() {
  let outDir = "";
  return {
    name: "seo-static-pages",
    apply: "build",
    configResolved(cfg) {
      outDir = path.resolve(cfg.root, cfg.build.outDir);
    },
    writeBundle: {
      order: "post",
      handler() {
        const tplPath = path.join(outDir, "index.html");
        const tpl = fs.readFileSync(tplPath, "utf8");
        // 首页也要处理:模板头是通用值,正文是空的
        fs.writeFileSync(tplPath, renderPage(tpl, SEO["/"], absUrl("/"), "/"), "utf8");
        for (const p of SNAPSHOT_PATHS) {
          const dir = path.join(outDir, p.replace(/^\//, ""));
          fs.mkdirSync(dir, { recursive: true });
          fs.writeFileSync(path.join(dir, "index.html"), renderPage(tpl, SEO[p], absUrl(p), p), "utf8");
        }
      },
    },
  };
}

One note: order: "post" ensures it runs after other plugins. If multiple plugins want to modify index.html, execution order can be disrupted. In that case, explicitly specify enforce.

4.3 renderPage: Strip Comments, Then Clear Head, Then Write Head

This is the step most prone to bugs, with two pitfalls stacked together.

Pitfall A: The template has a default <title>. Just appending will produce two titles per page, and search engines can't be sure which one to take.

Pitfall B: Direct regex deletion can accidentally kill comments. Our index.html comments contain examples like <meta>. Regex matching tags in comments will cut the comment in half, leaving a stray --> in the <head>.

So the order must be first strip HTML comments, then delete tags:

function stripTemplateHead(html) {
  // 1) 先剥 HTML 注释(注释里也可能含 <meta> 示例,先删标签会把注释切坏)
  return html
    .replace(/<!--[\s\S]*?-->/g, "")
    .replace(/<title>[\s\S]*?<\/title>/gi, "")
    .replace(/<meta[^>]*name="description"[^>]*>/gi, "")
    .replace(/<meta[^>]*name="keywords"[^>]*>/gi, "")
    .replace(/<meta[^>]*name="robots"[^>]*>/gi, "")
    .replace(/<link[^>]*rel="canonical"[^>]*>/gi, "")
    .replace(/<link[^>]*rel="alternate"[^>]*>/gi, "")
    .replace(/<meta[^>]*property="og:[^"]*"[^>]*>/gi, "");
}

Honestly, using regex on HTML is a compromise. The fundamental fix is to bring in cheerio or parse5 to parse into a DOM tree and then operate. But for this one action to add a dependency to the build chain, I think it's not worth it — provided the template HTML structure stays stable, no nested weird tags, and no tags inside comments that regex would hit. This has to be communicated within the team, otherwise someday someone adds a comment to index.html and the build silently breaks.

Write head tags:

const head = [
  `<title>${esc(seo.title)}</title>`,
  `<meta name="description" content="${esc(seo.description)}" />`,
  `<meta name="robots" content="${NOINDEX.includes(p) ? "noindex,follow" : "index,follow"}" />`,
  `<link rel="canonical" href="${url}" />`,
  `<meta property="og:url" content="${url}" />`,
  `<meta property="og:title" content="${esc(seo.title)}" />`,
].join("\n    ");
out = out.replace("</head>", `  ${head}\n  </head>`);

The regex list for clearing head must align with the tags actually present in the template. If the template adds twitter:* tags, you need to add a corresponding regex, otherwise two sets will appear again.

4.4 Structured Data: One Injection Covers Entities + Breadcrumb

AI search (Doubao, Kimi, Perplexity) reads JSON-LD first to judge "what you are." Using @graph to put multiple entities into one <script> is cleaner than multiple scattered blocks:

function buildJsonLd(path, seo) {
  const url = absUrl(path);
  const graph = [
    {
      "@type": "Organization",
      "@id": SITE_ORIGIN + "/#organization",
      name: "Acme Data API",
      url: SITE_ORIGIN + "/",
      email: "[email protected]", // 示例值,别写真实邮箱
    },
  ];
  if (SERVICE_PAGES.includes(path)) {
    graph.push({
      "@type": "Service",
      "@id": url + "#service",
      name: seo.h1,
      url,
      serviceType: "Data API",
      provider: { "@id": SITE_ORIGIN + "/#organization" },
    });
  }
  graph.push({
    "@type": "BreadcrumbList",
    itemListElement: [
      { "@type": "ListItem", position: 1, name: "首页", item: absUrl("/") },
      { "@type": "ListItem", position: 2, name: seo.h1, item: url },
    ],
  });
  return { "@context": "https://schema.org", "@graph": graph };
}

There's a required escape when injecting:

const ld = JSON.stringify(buildJsonLd(p, seo)).replace(/</g, "\u003c");
out = out.replace("</head>", `  <script type="application/ld+json">${ld}</script>\n  </head>`);

JSON.stringify does not escape <. If the data contains </script> or any text starting with <, it will prematurely close the script tag and execute the following HTML as code — that's the root cause of pitfall 2.

4.5 Pre-place Static Body in #app

After the title changes, the body is still empty. Stuff a piece of plain HTML into the mount point. Vue runtime will replace it entirely when mounting. Users don't see it, crawlers do:

const snapshot =
  snapshotHtml ||
  buildSnapshot(p, seo) || // 每页静态正文:小标题 + 列表 + 数据 + 常见问题 + 内链
  `<h1>${esc(seo.h1)}</h1><p>${esc(seo.description)}</p>`;
out = out.replace(
  /<div id="app"><\/div>/,
  `<div id="app"><div class="seo-snapshot">${snapshot}</div></div>`
);

buildSnapshot includes, in addition to the main body, two fixed extra blocks: related page internal link matrix and FAQs. These two blocks are more effective than the body — internal links solve crawl depth, FAQs hit long-tail keywords, and can be directly extracted as answers by AI through FAQPage structured data.

4.6 Generate Sitemap While You're At It

lastmod and changefreq are in the config, so there's no reason to maintain sitemap by hand:

const today = new Date().toISOString().slice(0, 10);
const entry = (p) => `  <url>
    <loc>${absUrl(p)}</loc>
    <lastmod>${today}</lastmod>
    <changefreq>${p === "/" ? "daily" : "weekly"}</changefreq>
  </url>`;
fs.writeFileSync(path.join(outDir, "sitemap.xml"), urlset, "utf8");

Additionally, make a separate Chinese-only sitemap-zh.xml: Baidu barely indexes English pages, and putting English URLs in the same file only dilutes its crawl allocation. Google and Bing continue to use the full version with xhtml:link.

5. Verification Results

Build log:

[seo-static-pages] 生成 21 个静态页面(中文 12 / 英文 9)+ sitemap.xml 20 条
[seo-static-pages] 生成 llms.txt(2187 字符)+ llms-full.txt(23760 字符)

Per-page actual tests (curl for status code and byte count):

Path Status Bytes Static body word count
/ 200 10,921 about 1,900
/bid/zhejiang/ 200 13,241 3,511
/housing/ 200 9,466 2,400+
/api-docs/ 200 9,273 2,100+
/kaoyan/ 200 6,424 1,657

The homepage dropped from 12,653 bytes to 10,921 bytes; the difference is the stripped HTML comments.

Before/after comparison:

Metric Before After
Pages with unique TDK 1 (all share homepage head) 21
Crawler-visible body text 0 (all in JS) 1,657 ~ 3,511
Structured data none @graph per page (Organization / Service / BreadcrumbList / FAQPage)
site: results 7, all old-site URLs Old-site paths get unified 410, new pages gradually replace

One more verification: UA for GPTBot, ClaudeBot, PerplexityBot, and Bytespider fetched homepage and inner pages, all returned 200 and could read the full body — so the claim that "AI doesn't directly crawl web pages, only Baidu index" is false. AI crawlers crawl more actively than expected.

6. Pitfalls Encountered

Pitfall 1: Page has two <title> tags. The symptom was search result titles being inconsistent. The cause: the template had a default title, and I appended another. Solution: in renderPage, first strip all common head tags, then write the dedicated ones.

Pitfall 2: After JSON-LD injection, the lower half of the page style collapsed. The symptom was misaligned structure after </script>. The cause: < in the data prematurely closed the script tag. Solution: after JSON.stringify, replace < with \u003c.

Pitfall 3: Canonical pointed to a URL that would 301. The symptom: webmaster tools reported "canonical does not match actual URL." The cause: nginx adds a trailing slash to directories, causing a 301, but my canonical missed the slash, making search engines index a version they got redirected away from. Solution: absUrl() uniformly appends /, so canonical, sitemap, and actual URL all agree.

Pitfall 4: Any garbage URL returns 200. The most hidden problem of SPA. The try_files fallback swallows all paths, and search engines think you have many pages with identical content. Solution: add a strict 404 in nginx (for static suffixes like .html / .xml / .txt, use try_files $uri =404), and the front-end catch-all route renders a real 404 page with noindex,follow. Double insurance.

Pitfall 5: The position: sticky announcement bar on the homepage wouldn't move inside el-main. After a long investigation, I realized Element Plus's el-main has overflow-x: hidden by default, and an ancestor with non-visible overflow creates a new scroll container, changing sticky's reference. Solution: change to position: fixed, and use padding-top: calc(15vh + 68px) to compensate.

7. The Value of This Approach in Real Projects

This is not a "SEO for blogs" trick. It's more valuable in enterprise projects:

From a full-stack perspective, this approach is worth promoting because it almost doesn't touch the backend. My main tech stack is Django REST framework + Vue3. The standard form for data API projects is "front-end SPA + independent API service," fully decoupled. In this architecture, solving SEO at runtime means either going SSR (an extra Node service to deploy, monitor, and scale) or letting Django render templates (giving up front-end/back-end separation). Build-time pre-rendering costs zero new services: it doesn't enter production, doesn't occupy server memory, and if something goes wrong it only affects the build. Rollback is just rebuilding once.

8. One Last Pitfall: Don't Turn Pre-rendering into Cloaking

The pre-placed static body snapshot must remain highly consistent with the content Vue actually renders. It's a static version of the same content, not a separate keyword page prepared for crawlers.

If the snapshot and what users see differ too much, the nature changes from "pre-rendering" to "content hiding (Cloaking)," which will be punished by search engines. Pre-rendering itself is an approach explicitly recognized by Google, but the premise is that the content is real. That's also why I insist the snapshot be generated from the same data, and don't hand-write a separate set.

That's the complete implementation of this SPA SEO engineering. The "build-time injection + zero runtime cost" approach essentially pulls SEO from an "operations problem" back to a "build problem": what crawlers see is already determined at packaging time, with no runtime explanation cost.

If you're also doing SEO for Vue3 single-page sites, or have had problems with soft 404s caused by try_files fallback, feel free to share your handling in the comments.