You opened build/index.html from disk
What you get depends on the build.
Prerendered pages render but freeze. SvelteKit 2 writes relative paths by
default (kit.paths.relative is true), so a prerendered page links its CSS
as ./_app/immutable/assets/… and the styled HTML shows. The code that
hydrates the page is loaded as an ES module:
<script>
{
import("./_app/immutable/entry/start.BxQ1.js");
// …
}
</script>
Chrome and Edge refuse module imports from a file:// origin (the console says
Access to script … from origin 'null' has been blocked by CORS policy), so
the page never hydrates. Links still work as plain page loads, but anything
interactive is dead. The same CORS rule is explained in
CORS error from origin 'null'.
An SPA build is blank. The fallback page (200.html, 404.html or
index.html) must work at any URL, so SvelteKit writes it with absolute
/_app/… paths. On file:/// that is the root of your disk, every request
fails, and the empty <body> is all you get.
Neither has a config fix. Serve the folder over HTTP:
npx serve build
Or run npm run preview, which serves the production build with Vite.
GitHub Pages: _app 404s and paths.base
Two separate things break a SvelteKit site on GitHub Pages.
Jekyll eats _app. When Pages publishes from a branch it runs Jekyll,
and Jekyll skips every file and folder that starts with _. The HTML is
published; _app/ is not. Add an empty .nojekyll file to static/, which
SvelteKit copies into build/:
touch static/.nojekyll
Deploying with the actions/deploy-pages workflow skips Jekyll, so this only
bites branch deploys. Renaming the folder with kit.appDir also works.
A project site lives below the root. https://user.github.io/repo/ must
know it is not at /. Set the base path from the environment so dev still
runs at the root:
// svelte.config.js
import adapter from "@sveltejs/adapter-static";
export default {
kit: {
adapter: adapter({ fallback: "404.html" }),
paths: {
base: process.argv.includes("dev") ? "" : process.env.BASE_PATH,
},
},
};
BASE_PATH=/repo npm run build
base must start with / and have no trailing slash. fallback: "404.html"
is the GitHub Pages trick for client-side routes: Pages serves 404.html for
any unknown path, and the app routes from there.
paths.base does not rewrite paths you wrote by hand:
| Written as |
With base: "/repo" it requests |
Fix |
<a href="/about"> |
/about (404) |
href="{base}/about" |
<img src="/logo.png"> |
/logo.png (404) |
src="{base}/logo.png", or import the file |
fetch("/data.json") |
/data.json (404) |
fetch(`${base}/data.json`) |
goto("/settings") |
/settings |
goto(`${base}/settings`) |
base comes from $app/paths. Recent SvelteKit releases also export a
resolve() helper there that adds it for you. With a custom domain the site
is at / again, so build without BASE_PATH.
Build errors
adapter-static refuses to build rather than ship a page that can't work.
Error: @sveltejs/adapter-static: all routes must be fully prerenderable,
but found the following routes that are dynamic:
- src/routes/dashboard
A static host can only serve files, and that route wasn't written as one.
Pick one of two fixes:
- Prerender everything. Add
export const prerender = true; to
src/routes/+layout.js (or +layout.ts). Every page now renders to HTML at
build time, and load functions run once during the build.
- Fall back to the browser. Set
fallback: "200.html" in the adapter
options. Routes that aren't prerendered are rendered client-side from that
page. Avoid naming the fallback index.html if you prerender /, because
the two would write the same file. Set export const ssr = false; in the
root layout for a pure SPA.
Error: 404 /docs/old-page (linked from /docs)
During prerendering SvelteKit crawls every link it finds, and a link to a page
that doesn't exist fails the build. Fix or remove the link. If the target
exists outside SvelteKit (a file in another deploy), set
kit.prerender.handleHttpError: "warn" in svelte.config.js to log it
instead of failing.
Refresh and deep links 404
The home page loads and client-side navigation works, but refreshing
/about or opening it from a link returns 404.
By default (trailingSlash: "never") SvelteKit writes one file per route:
build/
├── index.html
├── about.html
└── blog/
└── first-post.html
GitHub Pages, Netlify and Vercel serve about.html for /about. S3, nginx,
Apache and most CDNs look for a file or folder called about. Either change
the output in the root layout:
// src/routes/+layout.js
export const prerender = true;
export const trailingSlash = "always";
which writes about/index.html, or tell the server to try the .html file:
| Host |
Serve about.html for /about |
| nginx |
try_files $uri $uri.html $uri/ =404; |
| Apache |
RewriteCond %{REQUEST_FILENAME}.html -f + RewriteRule |
| Firebase |
"cleanUrls": true in firebase.json |
| S3/CloudFront |
trailingSlash = "always" (S3 has no extension fallback) |
Dynamic routes only exist if the crawler found them. /blog/[slug] is
prerendered for every slug linked from another prerendered page. A post that
nothing links to is never written. List them yourself with an entries
export next to the page:
// src/routes/blog/[slug]/+page.js
export async function entries() {
const posts = await import("$lib/posts.json");
return posts.default.map((p) => ({ slug: p.slug }));
}
Or add them to kit.prerender.entries in svelte.config.js. With a fallback
page, unlisted routes still render client-side, but only on hosts configured
to serve the fallback for unknown paths.
Stale chunks after a deploy
TypeError: Failed to fetch dynamically imported module:
https://example.com/_app/immutable/nodes/2.Cx9a.js
A visitor's tab (or a CDN) still holds the old HTML, which imports hashed
chunks the new build replaced. Serve HTML with Cache-Control: no-cache and
_app/immutable/ with a long immutable cache. SvelteKit can detect a new
version and do a full page load on the next navigation: set
kit.version.pollInterval to a number of milliseconds and check updated
from $app/state ($app/stores in older versions).
If the Network tab shows the chunk came back as HTML, the path is wrong
instead: see the paths.base section.
Environment variables
A static build has no server, so every value the browser sees is baked in when
you run npm run build.
- Use
$env/static/public, and prefix the variable with PUBLIC_. Variables
without the prefix never reach the browser.
- Set the variable in the build environment (the CI job), not on the host.
Setting it in the GitHub Pages or Netlify dashboard after the build changes
nothing.
$env/dynamic/public and $env/dynamic/private can't be read while
prerendering, and the build fails if a prerendered page tries.
Server features
These need a running server and are missing from build/:
- Form actions (
export const actions in +page.server.js). The form
posts to a static file and gets a 405 or a 404. Handle the submit in the
browser and call an external API.
+server.js endpoints that run per request. A GET endpoint on a
prerendered route is written once as a static file; anything that reads the
request is not.
+page.server.js load on a prerendered page runs at build time only.
The data is frozen into the build until you rebuild.
- Hooks in
hooks.server.js, cookies and redirects at request time.
Stop sending the build folder
Every file-based fix above has a ceiling: the person you send build/ to
still needs a local server, because module scripts don't run from disk. A
build preview works best as a URL.
Comma takes the build/ folder or a zip of it and returns one link. Assets
upload alongside the HTML with their references rewritten, so the _app,
paths.base and file:// problems don't apply, and reviewers comment on the
exact element they mean instead of sending a screenshot.
Share a SvelteKit build has the steps.
Two honest caveats. Reports run in a sandboxed iframe with scripts enabled but
no same-origin access, so code that reads localStorage or cookies without a
try/catch throws there. And leave paths.base unset for a preview build;
it bakes in a path the preview isn't served from.
Publish a build preview →
Related