One HTML File, Two Apps: Making a Hash-Routed SPA's Home Page Crawlable Without Touching the Router
2026-11-26
|
17 mins to read
|
Share article
"Just get rid of the # in the URL" sounds like a one-line router change. It isn't, and the # turned out not to be the real problem anyway. Crawlers couldn't read our content because the HTML didn't contain any. On top of that, giving the home page a clean URL runs into a constraint that's easy to miss: a domain's root path can only serve one file. This post is about how I got a marketing home page, full text and all, in front of search engines without changing how the admin app routes.
- Symptom: A Vue 3 + Vite admin app with hash routing. The marketing home page is just another route in that app, at
https://www.example.com/#/landing/home. We wanted it to show up in search, but a crawler hitting the domain root got a 4 kB shell with a loading spinner and nothing else. - Constraints: No admin URL could change. That includes
/#/login, short links already sent out by SMS, and third-party login callbacks. The test environment also lives in a subdirectory of a shared domain, where a server-side fallback isn't available. - What you'll take away: How I chose between three options, a reusable way to serve two apps from one
index.html, the skeleton of a build-time prerender plugin, and four problems that only show up once you actually ship this.
1. Where It Started: Is # Really the Problem?
Let's look at what a crawler actually gets. A request to https://www.example.com/ came back with roughly this:
<head>
<title>Admin</title>
</head>
<body>
<div id="app"><!-- just a loading spinner --></div>
<script type="module" src="./assets/js/index-xxxx.js"></script>
</body>
No body text, no description, no og: tags for link previews. robots.txt and sitemap.xml returned the very same HTML, because the static host serves the home page for any path that doesn't exist.
Now for the #. Everything after the # in a URL (the fragment) never leaves the browser. It isn't sent to the server at all. That has two consequences:
- As far as a crawler is concerned,
/#/landing/home,/#/login, and/#/anythingare all the same URL:/. Pages behind hash routing can't be indexed individually. - The server can't do anything about the
#. The first thing I asked was whether ops could just add a rule. They can't. All ops can control is what a given path returns, say a 302 from/landing/hometo/#/landing/home. The link you share looks clean, but the#is back in the address bar the moment it loads, and a crawler following the redirect drops the fragment and indexes/anyway. The front-end router puts the#there, so the front end has to take it away.
So this is really two separate problems tangled together:
| Problem | What causes it | Does dropping the # fix it? |
|---|---|---|
| The home page has no clean URL of its own | How hash-routed URLs are shaped | Yes |
| Crawlers can't read the body text | Everything is rendered client-side | No |
Googlebot does run JavaScript, but rendering happens in a deferred second pass that's slow and not guaranteed. Link-preview scrapers, and most crawlers that only read raw HTML, don't run JS at all. The second problem is the one that matters for SEO. Dropping the # is just a prerequisite.
2. Three Options and One Constraint You Can't Get Around
There were three obvious ways to go.
Option 1: move the whole app to history mode. Swap createWebHashHistory for createWebHistory, and URLs turn into /login and /landing/home. The catch is that every admin URL changes, so old links need a compatibility shim. The relative asset base ./ has to become absolute, or /landing/home will go looking for /landing/assets/.... And every environment's static host needs a 404 fallback, which my test environment, tucked into a subdirectory of a shared domain, can't have.
Option 2: pull the home page out into its own project on the same domain. This is the cleanest way to organize the code. But it runs straight into the constraint:
/#/login, which the server sees as plain / because the fragment never arrives. So you can't have both "the home page owns the domain root" and "admin URLs stay the same" through deployment alone. Either the home page gives up the root and moves into a subdirectory, leaving the admin shell as the site's front page, or the admin app moves to /app/ and every one of its URLs changes. The server simply can't tell someone who came for the home page from someone who came to log in.Option 3: use history mode for the home page only and leave everything else on hash. You'd pick the router instance at startup based on the URL. It works, but now a single app runs two routing modes and your navigation guards have to handle crossing between them. It also only fixes the URL, not the missing content.
Every option came with a cost I wasn't willing to pay. But turn that constraint around and it becomes the answer: if the root path can only serve one file, make that one file do two jobs.
| Full history mode | Separate project | One HTML, two apps | |
|---|---|---|---|
| Home page URL | /landing/home | / or a subdirectory, not both | / |
| Admin URLs | All change | Either unchanged or all change | Unchanged |
| Needs a server fallback | Yes | Partly | No |
| Crawlers can read the body | No, still client-rendered | Yes | Yes |
| Home page and admin ship independently | No | Yes | No |
That last row is what it costs. More on that in section 8.
3. The Approach: One HTML File, Two Apps
The whole idea fits in a sentence: index.html ships with the home page's complete static content already in it, and a tiny inline script at the very top checks the hash in the address bar to decide whether this page load should run the home page code or the admin code.
That keeps all three audiences happy at once:
- Crawlers request
/and get HTML with body text, a title, and a description. Whether they run JS no longer matters. - Home page visitors see a clean
/in the address bar. The home page entry never loads vue-router, and the hash router was the only thing adding#/in the first place. - Admin users notice nothing. Hash routing, the deploy directory, and every link out in the wild stay exactly as they were.
So where does the static content come from? At build time, I render the home page component once with Vue's server renderer and write the result into the built index.html:
To be clear, this isn't SSR at runtime. There's no Node server, and the output is still a folder of static files that gets uploaded to object storage like before. This is usually called prerendering, or static generation.
4. Implementation
4.1 The boot script
It sits in <head> and has to be inline and synchronous, since it needs to finish before the browser paints anything:
<script>
(function () {
var hash = location.hash;
var path = hash.replace(/^#/, "").split("?")[0].replace(/\/+$/, "");
var isAdminHash = /^#\//.test(hash) && path !== "" && path !== "/landing" && path !== "/landing/home";
// An existing short link, /m, only gets here because unknown paths fall back to index.html. Hand it back to admin
var isShortEntry = /\/m$/.test(location.pathname);
var landing = !isAdminHash && !isShortEntry;
window.__LANDING__ = landing;
document.documentElement.className += landing ? " boot-landing" : " boot-admin";
if (landing) {
// Tidy old URLs like /#/landing/home and /#/ into a clean one, without a reload
if (/^#\//.test(hash)) history.replaceState(history.state, "", location.pathname + location.search);
} else {
document.title = "Admin";
}
})();
</script>
Four things worth pointing out:
- Only a hash that starts with
#/counts as a route. A plain anchor like#section, or a fragment some ad platform tacked on, still means the home page. - Track down everything that quietly relies on the fallback. The static host serves
index.htmlfor unknown paths, and we had a short link,/m, that depended on exactly that: it would land in the admin app, and the router would rewrite it to a mobile page. After the split it would have been mistaken for the home page, so the script excludes it by path. Hidden dependencies like this aren't in any route table. The only way to find them is to go digging through code and config. - Old URLs get cleaned up with
replaceState, not a redirect. Any/#/landing/homelink already floating around opens with a clean address bar, costs no extra request, and keeps its query string. <title>defaults to the home page's title, since that's what crawlers read, and the script swaps it back for admin. Do it the other way around and any crawler that skips JS sees the admin title.
The real entry file does nothing but pick one:
// src/boot.ts
if (window.__LANDING__) {
import("./landing/main");
} else {
import("./main"); // the original admin entry, not one line changed
}
Because both are dynamic import() calls, the bundler splits them into two sets of chunks with nothing shared that shouldn't be. Home page visitors no longer pull down the admin bundle. Before this, the home page was a route inside the admin app, so every visitor downloaded the entire UI component library along with it.
4.2 The build plugin
I hooked prerendering onto the end of the build as a Vite plugin instead of adding another command to package.json. The reason is mundane: I wasn't sure which build command our release pipeline actually calls, and a plugin means it runs any time vite build runs.
// build/prerenderLanding.ts (skeleton)
export const prerenderLanding = (): Plugin => {
let config: ResolvedConfig;
let written = false;
return {
name: "prerender-landing",
apply: "build",
config: (_, { isSsrBuild }) => (isSsrBuild ? undefined : { build: { manifest: true } }),
configResolved: resolved => void (config = resolved),
writeBundle: () => void (written = true),
async closeBundle() {
// closeBundle also fires when the build fails, and the nested SSR build loads this plugin too
if (config.build.ssr || !written) return;
// 1. Run a second, SSR build with the same config, bundling only the home page's server entry
await build({
configFile: config.configFile,
mode: config.mode,
build: { ssr: "src/landing/entry-server.ts", outDir: ssrOutDir, copyPublicDir: false }
});
// 2. Render and write back into dist/index.html
const { render } = await import(pathToFileURL(ssrEntry).href);
const landingHtml = patchLandingHtml(await render());
html = html.replace(CONTAINER_RE, () => `<div id="landing-root" data-prerendered>${landingHtml}</div>`);
fs.writeFileSync(htmlPath, html);
}
};
};
The server entry is three lines that matter:
// src/landing/entry-server.ts
import { createSSRApp } from "vue";
import { renderToString } from "vue/server-renderer";
import Home from "@/views/landing/home.vue";
export const render = () => renderToString(createSSRApp(Home));
A few choices here deserve an explanation:
- The SSR build reuses the same
vite.config. Aliases, plugins, and asset naming are identical, so the image URLs coming out of the server render, content hashes included, line up with the client build's files. There's no mapping step. - The
writtenflag. Rollup callscloseBundleeven when the build fails. Without this guard, the plugin would try to patch anindex.htmlleft over from an earlier build, then throw an error that has nothing to do with what actually went wrong and bury the real one. - Pass a function to
replace, not a string. When the second argument toString.prototype.replaceis a string, sequences like$&and$1in it are treated as placeholders. Marketing copy with a$in it is hardly unusual (think prices), and the function form sidesteps the whole issue. - A failed prerender fails the build. It throws. I'd much rather ship nothing than quietly publish a home page with no body text. Nothing errors when that happens, and you only find out when traffic falls off.
4.3 The browser entry
// src/landing/main.ts
const container = document.getElementById("landing-root")!;
// By the time this module runs, its styles have loaded (the bundler waits for CSS dependencies)
document.getElementById("app")?.remove(); // drop the loading spinner
document.documentElement.classList.add("landing-ready"); // reveal the home page container
const prerendered = container.hasAttribute("data-prerendered");
const app = prerendered ? createSSRApp(Home) : createApp(Home);
app.mount(container);
// Going to admin from the home page only changes the hash. There is no router here,
// so reload once and let the boot script load admin
window.addEventListener("hashchange", () => {
if (isAdminHash(location.hash)) location.reload();
});
data-prerendered is a marker the build plugin leaves behind. Production builds have it, so the entry calls createSSRApp and hydrates, which means wiring events and reactivity onto the DOM that's already there instead of rebuilding it. In local dev the container is empty, so it falls back to a plain createApp. One entry file covers both cases, and the dev workflow doesn't change.
Buttons on the home page that used to call router.push("/overview") now just set location.hash = "#/overview". What I like about this is that it works whether or not there's a router. On the standalone home page it fires the hashchange listener above. The header and footer are also shared with a legal page that still lives in the admin app, and over there the hash router picks up the very same change.
5. Four Things That Only Bite Once You Ship
Pitfall 1: the content shows up before its styles
Once the page is prerendered, the home page's markup is in the DOM the instant the HTML arrives. Its CSS, though, is a dependency of the JS entry and loads a beat later. What you get is a flash of raw, completely unstyled HTML.
The fix is to collapse the container with an inline style in <head>, then let it go once the entry runs:
html.boot-landing:not(.landing-ready) #landing-root {
height: 0;
overflow: hidden;
visibility: hidden;
}
Crawlers don't care. The ones that skip JS parse the text and ignore visibility, and the ones that run JS see the final state. But it does mean prerendering didn't get the page in front of users any faster. That's a real limitation, and I come back to it in section 8.
Pitfall 2: the SSR build's asset URLs break under a subdirectory deploy
My base is the relative ./, so the same build works at a domain root or in any subdirectory. The client build resolves assets relative to the current file. The SSR build doesn't. Here's the branch in the Vite 5 source:
if (relative && !config.build.ssr) {
return toRelative(filename, hostId);
}
return joinUrlSegments(config.base, filename);
A relative base only kicks in for client builds. The SSR build emits URLs like /assets/png/xxx.png, anchored at the domain root. Production sits at the root, so it was fine. The test environment sits under /admin/, and every image there came back 404.
Here's the nasty part: hydration won't fix it for you. In production mode Vue doesn't patch static attributes when it hydrates, so whatever src the server wrote is what stays on the page. I had to rewrite the HTML before saving it:
html.replace(/\s(src|poster)="\/assets\//g, ' $1="./assets/');
You only see this when three things line up: a subdirectory deploy, a relative base, and prerendering. I didn't catch it until I ran a local static server that mimicked the subdirectory.
Pitfall 3: the browser downloads hidden content anyway
On an admin URL, the home page HTML is dead weight. The boot script sets it to display: none, and a script immediately after it removes the node altogether. That sounds airtight, but browsers have a preload scanner. It races ahead of the main parser through the raw HTML and kicks off requests for images and other resources early. It has no idea those elements are about to be hidden or thrown away.
The home page has more than seventy images. Do nothing, and every admin user downloads all of them for no reason.
The fix is to stamp loading="lazy" on every image during prerendering. The preload scanner leaves lazy images alone, and a lazy image inside a hidden container never reaches the viewport, so it's never requested. Video posters don't have a lazy equivalent, so I stash poster in a data- attribute and put it back right before the home page entry mounts.
What I measured in Chrome: on an admin URL, zero requests for the home page's images or video posters. I haven't checked how the preload scanner behaves in other browsers.
Pitfall 4: removing the loading spinner took the page margins with it
I did this one to myself. In the original index.html, the few lines of CSS that zero out the margins on html, body lived in a <style> tag inside <div id="app">, right beside the loading spinner. When the admin app mounts it takes over #app, and its own global stylesheet has the same reset, so nobody ever noticed.
My home page entry calls document.getElementById("app").remove(). The <style> tag went out with it, the standalone entry doesn't load the admin's global styles, and body snapped back to the browser's default 8px margin. The whole page picked up a white border.
The fix is simple: move the reset into an inline style in <head>, so it no longer hangs off a node that's going to be removed.
<head>
<style>
html,
body {
width: 100%;
height: 100%;
padding: 0;
margin: 0;
}
</style>
</head>
I left the original copy inside #app alone. The admin entry still works the way it always has, and deduplicating two CSS rules isn't a good enough reason to touch a path that's been running fine for a long time.
The real lesson here is bigger than 8px: when a node is removed, any <style> inside it stops applying, and nobody keeps track of which node a global style happens to live in. If you're about to delete or replace a container that was already on the page, check first whether it's carrying styles or scripts along with it.
Type checking passed. Lint passed. The build passed. Every piece of runtime state my script read was correct. It took a screenshot to catch it. More on that in the takeaways.
6. Getting Preloading Back After the Entries Went Dynamic
Before any of this, the <script type="module"> in the HTML pointed straight at the admin entry, and the bundler emitted <link rel="modulepreload"> tags for its static dependencies. The browser could start downloading them in parallel as soon as it parsed <head>.
Now the HTML points at boot.ts, which is a handful of lines, and both real entries are dynamic import() calls. Bundlers don't emit preload tags in the HTML for dynamic entries. So the browser has to download and run boot.ts before it even knows what to fetch next. That's one extra round trip, and a performance regression for admin users that I wasn't going to accept.
To fix it, the build plugin reads Vite's manifest, which records the output file for each entry and the files it statically depends on. From that it works out what each of the two entries needs on first load, and injects an inline script just before </head>:
var files = window.__LANDING__ ? manifest.landing : manifest.admin;
files.js.forEach(function (f) { add("modulepreload", f); });
files.css.forEach(function (f) { add("preload", f, "style"); });
There's one part of this that's easy to get wrong: the CSS goes in as rel="preload" as="style", not as a stylesheet.
<link rel="stylesheet">?Before Vite loads a dynamic entry at runtime, it takes care of that entry's CSS. Its preload helper has this check (Vite 5):if (link.href === dep && (!isCss || link.rel === "stylesheet")) {
return; // a stylesheet with this URL is already on the page: bail out, don't wait
}
rel="preload" link doesn't match that condition, so Vite still inserts its own stylesheet and waits for the load event. By then the file is already cached, so the wait is close to free. You get the warm cache and the correct execution order.crossOrigin also has to match what Vite puts on its own tags, which is an empty string. If it doesn't, the two requests use different credentials modes and the browser won't reuse the cached response.The manifest is deleted once it's been read. It never ships.
One more manifest gotcha. I first looked up the admin entry by its source path, src/main.ts, and it wasn't there. Something in the admin code imports the entry file back, so the bundler folded it into a shared chunk keyed by a hashed chunk name. I ended up finding it through the HTML entry's dynamicImports instead: it's whichever one isn't the home page.
7. Verification: Driving a Real Browser Without a Test Library
All the risk in a change like this is at runtime. What does the address bar end up showing? Which resources got requested? Did hydration complain? Type checks and a green build can't tell you any of that.
I didn't reach for Puppeteer or Playwright. I talked to Chrome directly over the Chrome DevTools Protocol (CDP): launch the local Chrome with --headless=new --remote-debugging-port and send protocol commands over a WebSocket. On Node 20, --experimental-websocket turns on the built-in WebSocket client, so there's nothing to install:
const send = (method, params = {}) =>
new Promise(resolve => {
const id = ++seq;
pending.set(id, resolve);
ws.send(JSON.stringify({ id, method, params }));
});
await send("Page.navigate", { url });
const state = await send("Runtime.evaluate", {
expression: `JSON.stringify({ href: location.href, hasApp: !!document.getElementById("app") })`,
returnByValue: true
});
Next to it runs a static server, about twenty lines long, that serves the build output from a subdirectory and from the domain root at the same time. That covers both the test setup and production, including production's habit of serving the home page for unknown paths. The server also logs every request path, which is how I can actually back up a claim like "zero home page image requests on an admin URL."
I ran nine URLs through it, and for each one read back the final address, the title, the DOM state, and any console errors:
| Scenario | What I checked |
|---|---|
| Home page, once in a subdirectory and once at the root | No # in the address; container hydrated; no console errors; no broken images in the subdirectory |
Old URLs #/landing/home and /?utm=x#/ | Address cleaned up, query string intact |
Admin URL #/login | Home page container gone; zero requests for home page images, posters, or styles |
| Clicking through to admin from the home page | One reload, then the login page |
| Navigating to the root path from inside admin | Full reload back to the home page, no # |
| The legal page inside admin | Shared header and footer links work |
Short link /m | Still reaches the mobile page instead of being treated as the home page |
Last, I used Page.captureScreenshot to grab three screenshots and looked at them myself. That's where pitfall 4 turned up.
8. Where This Approach Falls Short
None of this is free, so here's what it costs.
What it doesn't fix
- Users don't see the page any sooner. The hero's intro animation waits for JS to add a state class before it fades in. Combine that with the hiding from pitfall 1, and content shows up at about the same moment it did before. Prerendering decides whether content can be read, not how quickly it's seen. Page experience metrics are a separate job.
- Only one page benefits. The legal page and everything else are still hash routes.
- Unknown paths still return 200. The static host's fallback hasn't changed. A
canonicaltag tells search engines the domain root is the real address.
What it adds
- The entry HTML got heavier.
index.html, which is only a shell, went from about 4 kB to about 98 kB, or roughly 17 kB gzipped, and the extra home page markup is no use to admin users. My first version was actually 165 kB (40 kB gzipped), and two trims brought it down. First, the contact modal, which only appears on click, now renders in the browser only. It's worthless to crawlers, yet its template is packed with inline icons. Second, the home page's small images are no longer inlined as data URIs. As separate files they also get lazy loading for free. What's left is only paid on a full page load, since in-app route changes never re-request the HTML. Next to the roughly 1.8 MB of JavaScript the admin app loads up front (uncompressed, about 590 kB gzipped), it's a small fixed cost. - The home page and admin still ship together. Fixing a typo on the home page means releasing the entire admin app. If the home page is going to grow into a multi-page content site, this is the wrong approach. At that point, split it into its own project and accept that the admin app has to move.
- Home page components now come with rules. They have to render in Node, which means no top-level
windowordocument, and nothing that differs between server and client, like random numbers or the current time. The build fails if you break this, but whoever edits those components needs to know the rule going in. - There's build code to re-test on every bundler upgrade. The plugin leans on the shape of the manifest and on how the SSR build treats a relative base. Neither is a stable public contract.
- The routing check lives in two places. An inline script can't
import, so the hash rule is written once in the HTML and once in TypeScript, with nothing but comments keeping them in sync.
9. Takeaways
- Work out which problem you actually have before you touch anything. The ask was "get rid of the
#." The goal was "be readable by search engines." The first is just one prerequisite for the second. Take the ask literally and you end up with a lovely clean URL on a page crawlers still see as an empty shell. - Flip a constraint around and it often turns into the design. "The root path can only serve one file" killed two obvious options and pointed directly at a third: make that file do two jobs. When a constraint has you stuck, it's worth asking what things would look like if the constraint were part of the design.
- What you add shouldn't cost anything for the people who don't use it. Home page visitors and crawlers benefit here, but the change lands in an entry point everyone shares. Getting preloading back, lazy-loading the images, and deferring the posters are all there so admin users don't pay for a feature that has nothing to do with them. When you're weighing an approach, give "impact on unrelated paths" a column of its own.
- A silent failure is worse than a loud one. Failing the build when prerendering fails, and refusing to patch stale output when the build fails, both exist to surface problems before release. That matters most for SEO work, because nobody files a bug when it breaks.
- Screenshots catch what assertions miss. That 8px white border sailed through every automated check. If a change touches rendering, get a person to look at the actual page, even if that person is you.