Repository: sveltejs/kit (js)

Issue:
invalid static requests return index.html instead of 404
### Describe the bug

If the home page `/` is prerendered, invalid static requests (those matching the paths in `_routes.json` `excluded` but are not found) such as `/_app/abcd`, incorrectly return a `200` status code and the content of the prerendered `/index.html` file if any.

However, if a `404.html` file is found, it is returned alongside the expected 404 status code.

### Reproduction

1. Find a Cloudflare Pages website deployed with `@sveltejs/adapter-cloudflare`.
2. Navigate to a non-existent `/_app/*` URL.

For example, the URL below should return a 404 but returns the prerendered home page:

https://brgh.church/_app/doesntexist

### Logs

_No response_

### System Info

```Shell
System:
    OS: macOS 13.2
    CPU: (8) arm64 Apple M1 Pro
    Memory: 142.81 MB / 32.00 GB
    Shell: 5.8.1 - /bin/zsh
  Binaries:
    Node: 16.18.0 - ~/.nvm/versions/node/v16.18.0/bin/node
    Yarn: 3.2.3 - ~/.nvm/versions/node/v16.18.0/bin/yarn
    npm: 8.19.2 - ~/.nvm/versions/node/v16.18.0/bin/npm
  Browsers:
    Chrome: 110.0.5481.77
    Chrome Canary: 112.0.5586.0
    Firefox: 109.0.1
    Firefox Developer Edition: 110.0
    Safari: 16.3
    Safari Technology Preview: 16.4
  npmPackages:
    @sveltejs/adapter-cloudflare: ^2.0.1 => 2.0.1 
    @sveltejs/kit: ^1.3.10 => 1.3.10 
    svelte: ^3.55.1 => 3.55.1 
    vite: ^4.1.1 => 4.1.1
```


### Severity

annoyance

### Additional Information

When the root page is not prerendered, invalid requests to `/_app/*` return a blank page and a 404.
So, should the Cloudflare adapter include a `/404.html` by default to ensure this occurs consistently?
Or is it enough to document the importance of including a `404.html` page?

Pull request:
always generate `404.html`
* closes #9011
* closes #9245 (which this PR builds on)

If the user creates their own 404 route or static asset, that will be given priority.

### Please don't delete this checklist! Before submitting the PR, please make sure you do the following:
- [x] It's really useful if your PR references an issue where it is discussed ahead of time. In many cases, features are absent for a reason. For large changes, please create an RFC: https://github.com/sveltejs/rfcs
- [x] This message body should clearly illustrate what problems it solves.
- [ ] Ideally, include a test that fails without this PR but passes with it.

### Tests
- [ ] Run the tests with `pnpm test` and lint the project with `pnpm lint` and `pnpm check`

### Changesets
- [x] If your PR makes a change that should be noted in one or more packages' changelogs, generate a changeset by running `pnpm changeset` and following the prompts. Changesets that add features should be `minor` and those that fix bugs should be `patch`. Please prefix changeset messages with `feat:`, `fix:`, or `chore:`.


Patch:
diff --git a/.changeset/long-lobsters-love.md b/.changeset/long-lobsters-love.md
new file mode 100644
index 000000000..b056081aa
--- /dev/null
+++ b/.changeset/long-lobsters-love.md
@@ -0,0 +1,5 @@
+---
+'@sveltejs/adapter-cloudflare': minor
+---
+
+feat: generate `404.html`
diff --git a/.changeset/tall-impalas-report.md b/.changeset/tall-impalas-report.md
new file mode 100644
index 000000000..1cabd2e5a
--- /dev/null
+++ b/.changeset/tall-impalas-report.md
@@ -0,0 +1,5 @@
+---
+'@sveltejs/kit': patch
+---
+
+fix: always include `<link rel="stylesheet">`, even for stylesheets excluded from Link headers
diff --git a/.github/ISSUE_TEMPLATE/bug_report.yml b/.github/ISSUE_TEMPLATE/bug_report.yml
index 9cde91584..a94d39153 100644
--- a/.github/ISSUE_TEMPLATE/bug_report.yml
+++ b/.github/ISSUE_TEMPLATE/bug_report.yml
@@ -9,7 +9,7 @@ body:
     id: bug-description
     attributes:
       label: Describe the bug
-      description: Please check if bugs related to building are caused by Vite and [file there](https://github.com/vitejs/vite/issues) if appropriate. If you intend to submit a PR for this issue, tell us in the description. Thanks!
+      description: Please [check if bugs related to building are caused by Vite](https://github.com/sveltejs/kit#bug-reporting) and [file there](https://github.com/vitejs/vite/issues) if appropriate. If you intend to submit a PR for this issue, tell us in the description. Thanks!
       placeholder: Bug description
     validations:
       required: true
diff --git a/README.md b/README.md
index fb5282e9f..65ff09b6b 100644
--- a/README.md
+++ b/README.md
@@ -23,6 +23,12 @@ Web development, streamlined. Read the [documentation](https://kit.svelte.dev/do
 
 [Additional adapters](<(https://sveltesociety.dev/components#adapters)>) are maintained by the community.
 
+## Bug reporting
+
+Please make sure the issue you're reporting involves SvelteKit. Many issues related to how a project builds originate from [Vite](https://vitejs.dev/), which is used to build a SvelteKit project. You can create a new Vite project with `npm create vite@latest` for client-side only repros and `npm create vite-extra@latest` for SSR or library repros.
+
+If an issue originates from Vite, please report it in the [Vite issue tracker](https://github.com/vitejs/vite/issues).
+
 ## Contributing
 
 See [CONTRIBUTING.md](./CONTRIBUTING.md) for information on how to develop SvelteKit locally.
diff --git a/documentation/docs/25-build-and-deploy/50-adapter-static.md b/documentation/docs/25-build-and-deploy/50-adapter-static.md
index 6e7e81246..b417397e0 100644
--- a/documentation/docs/25-build-and-deploy/50-adapter-static.md
+++ b/documentation/docs/25-build-and-deploy/50-adapter-static.md
@@ -4,7 +4,7 @@ title: Static site generation
 
 To use SvelteKit as a static site generator (SSG), use [`adapter-static`](https://github.com/sveltejs/kit/tree/master/packages/adapter-static).
 
-This will prerender your entire site as a collection of static files. If you'd like to prerender only some pages, you will need to use a different adapter together with [the `prerender` option](page-options#prerender).
+This will prerender your entire site as a collection of static files. If you'd like to prerender only some pages and dynamically server-render others, you will need to use a different adapter together with [the `prerender` option](page-options#prerender).
 
 ## Usage
 
@@ -70,7 +70,7 @@ The directory to write static assets (the contents of `static`, plus client-side
 
 ### fallback
 
-Specify a [fallback page](#spa-mode-add-fallback-page) for SPA mode, e.g. `index.html` or `200.html` or `404.html`.
+Specify a fallback page for [SPA mode](single-page-apps), e.g. `index.html` or `200.html` or `404.html`.
 
 ### precompress
 
@@ -80,85 +80,6 @@ If `true`, precompresses files with brotli and gzip. This will generate `.br` an
 
 By default, `adapter-static` checks that either all pages and endpoints (if any) of your app were prerendered, or you have the `fallback` option set. This check exists to prevent you from accidentally publishing an app where some parts of it are not accessible, because they are not contained in the final output. If you know this is ok (for example when a certain page only exists conditionally), you can set `strict` to `false` to turn off this check.
 
-## SPA mode
-
-You can use `adapter-static` to create a single-page app or SPA by specifying a **fallback page**.
-
-> In most situations this is not recommended: it harms SEO, tends to slow down perceived performance, and makes your app inaccessible to users if JavaScript fails or is disabled (which happens [more often than you probably think](https://kryogenix.org/code/browser/everyonehasjs.html)).
-
-If you want to create a simple SPA with no prerendered routes, the necessary config looks like this:
-
-```js
-// @errors: 2307
-/// file: svelte.config.js
-import adapter from '@sveltejs/adapter-static';
-
-export default {
-	kit: {
-		adapter: adapter({
-			fallback: '200.html'
-		}),
-		prerender: { entries: [] }
-	}
-};
-```
-
-```js
-/// file: src/routes/+layout.js
-export const ssr = false;
-```
-
-You can also turn only part of your app into an SPA by [disabling prerendering](#spa-mode-turn-off-prerendering) only for those pages.
-
-Let's go through these options one by one:
-
-### Add fallback page
-
-The fallback page is an HTML page created by SvelteKit from your page template (e.g. `app.html`) that loads your app and navigates to the correct route. For example [Surge](https://surge.sh/help/adding-a-200-page-for-client-side-routing), a static web host, lets you add a `200.html` file that will handle any requests that don't correspond to static assets or prerendered pages. We can create that file like so:
-
-```js
-// @errors: 2307
-/// file: svelte.config.js
-import adapter from '@sveltejs/adapter-static';
-
-export default {
-	kit: {
-		adapter: adapter({
-			fallback: '200.html'
-		})
-	}
-};
-```
-
-> How to configure this behaviour does however depend on your hosting solution and is not part of SvelteKit. It is recommended to search the host's documentation on how to redirect requests.
-
-### Turn off prerendering
-
-When operating in SPA mode, you can omit the [`prerender`](page-options#prerender) option from your root layout (or set it to `false`, its default value), and only pages that have the `prerender` option set will be prerendered at build time.
-
-SvelteKit will still crawl your app's entry points looking for prerenderable pages. If `vite build` fails because of pages that can't be loaded outside the browser, you can set `config.kit.prerender.entries` to `[]` to prevent this from happening.
-
-You can also add turn off prerendering only to parts of your app, if you want other parts to be prerendered.
-
-### Turn off ssr
-
-During development, SvelteKit will still attempt to server-side render your routes. This means accessing things that are only available in the browser (such as the `window` object) will result in errors, even though this would be valid in the output app. To align the behavior of SvelteKit's dev mode with your SPA, you can add [`export const ssr = false`](page-options#ssr) to your root `+layout`. You can also add this option only to parts of your app, if you want other parts to be prerendered.
-
-### Apache
-
-To run an SPA on [Apache](https://httpd.apache.org/), you should add a `static/.htaccess` file to route requests to the fallback page:
-
-```
-<IfModule mod_rewrite.c>
-	RewriteEngine On
-	RewriteBase /
-	RewriteRule ^200\.html$ - [L]
-	RewriteCond %{REQUEST_FILENAME} !-f
-	RewriteCond %{REQUEST_FILENAME} !-d
-	RewriteRule . /200.html [L]
-</IfModule>
-```
-
 ## GitHub Pages
 
 When building for GitHub Pages, make sure to update [`paths.base`](configuration#paths) to match your repo name, since the site will be served from <https://your-username.github.io/your-repo-name> rather than from the root.
diff --git a/documentation/docs/25-build-and-deploy/55-single-page-apps.md b/documentation/docs/25-build-and-deploy/55-single-page-apps.md
new file mode 100644
index 000000000..c830470cb
--- /dev/null
+++ b/documentation/docs/25-build-and-deploy/55-single-page-apps.md
@@ -0,0 +1,61 @@
+---
+title: Single-page apps
+---
+
+You can turn any SvelteKit app, using any adapter, into a fully client-rendered single-page app (SPA) by disabling SSR at the root layout:
+
+```js
+/// file: src/routes/+layout.js
+export const ssr = false;
+```
+
+> In most situations this is not recommended: it harms SEO, tends to slow down perceived performance, and makes your app inaccessible to users if JavaScript fails or is disabled (which happens [more often than you probably think](https://kryogenix.org/code/browser/everyonehasjs.html)).
+
+If you don't have any server-side logic (i.e. `+page.server.js`, `+layout.server.js` or `+server.js` files) you can use [`adapter-static`](adapter-static) to create your SPA by adding a _fallback page_.
+
+## Usage
+
+Install with `npm i -D @sveltejs/adapter-static`, then add the adapter to your `svelte.config.js` with the following options:
+
+```js
+// @errors: 2307
+/// file: svelte.config.js
+import adapter from '@sveltejs/adapter-static';
+
+export default {
+	kit: {
+		adapter: adapter({
+			fallback: '200.html' // may differ from host to host
+		})
+	}
+};
+```
+
+The `fallback` page is an HTML page created by SvelteKit from your page template (e.g. `app.html`) that loads your app and navigates to the correct route. For example [Surge](https://surge.sh/help/adding-a-200-page-for-client-side-routing), a static web host, lets you add a `200.html` file that will handle any requests that don't correspond to static assets or prerendered pages.
+
+On some hosts it may be `index.html` or something else entirely — consult your platform's documentation.
+
+## Apache
+
+To run an SPA on [Apache](https://httpd.apache.org/), you should add a `static/.htaccess` file to route requests to the fallback page:
+
+```
+<IfModule mod_rewrite.c>
+	RewriteEngine On
+	RewriteBase /
+	RewriteRule ^200\.html$ - [L]
+	RewriteCond %{REQUEST_FILENAME} !-f
+	RewriteCond %{REQUEST_FILENAME} !-d
+	RewriteRule . /200.html [L]
+</IfModule>
+```
+
+## Prerendering individual pages
+
+If you want certain pages to be prerendered, you can re-enable `ssr` alongside `prerender` for just those parts of your app:
+
+```js
+/// file: src/routes/my-prerendered-page/+page.js
+export const prerender = true;
+export const ssr = true;
+```
\ No newline at end of file
diff --git a/documentation/docs/60-appendix/30-glossary.md b/documentation/docs/60-appendix/30-glossary.md
index 9b70b8dbc..b943eb009 100644
--- a/documentation/docs/60-appendix/30-glossary.md
+++ b/documentation/docs/60-appendix/30-glossary.md
@@ -36,7 +36,7 @@ In SvelteKit, client-side routing will be used by default, but you can skip it w
 
 A single-page app (SPA) is an application in which all requests to the server load a single HTML file which then does client-side rendering of the requested contents based on the requested URL. All navigation is handled on the client-side in a process called client-side routing with per-page contents being updated and common layout elements remaining largely unchanged. SPAs do not provide SSR, which has the shortcoming described above. However, some applications are not greatly impacted by these shortcomings such as a complex business application behind a login where SEO would not be important and it is known that users will be accessing the application from a consistent computing environment.
 
-In SvelteKit, you can [build a SPA with `adapter-static`](adapter-static#spa-mode).
+In SvelteKit, you can [build a SPA with `adapter-static`](single-page-apps).
 
 ## SSG
 
diff --git a/packages/adapter-cloudflare/index.js b/packages/adapter-cloudflare/index.js
index 177cb3514..c50191f61 100644
--- a/packages/adapter-cloudflare/index.js
+++ b/packages/adapter-cloudflare/index.js
@@ -1,5 +1,5 @@
 import { writeFileSync } from 'node:fs';
-import { posix } from 'node:path';
+import * as path from 'node:path';
 import { fileURLToPath } from 'node:url';
 import * as esbuild from 'esbuild';
 
@@ -16,11 +16,14 @@ export default function (options = {}) {
 			builder.rimraf(tmp);
 			builder.mkdirp(tmp);
 
+			// generate 404.html first which can then be overridden by prerendering, if the user defined such a page
+			await builder.generateFallback(path.join(dest, '404.html'));
+
 			const dest_dir = `${dest}${builder.config.kit.paths.base}`;
 			const written_files = builder.writeClient(dest_dir);
 			builder.writePrerendered(dest_dir);
 
-			const relativePath = posix.relative(tmp, builder.getServerDirectory());
+			const relativePath = path.posix.relative(tmp, builder.getServerDirectory());
 
 			writeFileSync(
 				`${tmp}/manifest.js`,
diff --git a/packages/kit/src/runtime/server/page/render.js b/packages/kit/src/runtime/server/page/render.js
index 5a64f8326..da2659fc4 100644
--- a/packages/kit/src/runtime/server/page/render.js
+++ b/packages/kit/src/runtime/server/page/render.js
@@ -235,20 +235,20 @@ export async function render_response({
 	for (const dep of stylesheets) {
 		const path = prefixed(dep);
 
-		if (resolve_opts.preload({ type: 'css', path })) {
-			const attributes = ['rel="stylesheet"'];
-
-			if (inline_styles.has(dep)) {
-				// don't load stylesheets that are already inlined
-				// include them in disabled state so that Vite can detect them and doesn't try to add them
-				attributes.push('disabled', 'media="(max-width: 0)"');
-			} else {
+		const attributes = ['rel="stylesheet"'];
+
+		if (inline_styles.has(dep)) {
+			// don't load stylesheets that are already inlined
+			// include them in disabled state so that Vite can detect them and doesn't try to add them
+			attributes.push('disabled', 'media="(max-width: 0)"');
+		} else {
+			if (resolve_opts.preload({ type: 'css', path })) {
 				const preload_atts = ['rel="preload"', 'as="style"'];
 				link_header_preloads.add(`<${encodeURI(path)}>; ${preload_atts.join(';')}; nopush`);
 			}
-
-			head += `\n\t\t<link href="${path}" ${attributes.join(' ')}>`;
 		}
+
+		head += `\n\t\t<link href="${path}" ${attributes.join(' ')}>`;
 	}
 
 	for (const dep of fonts) {


Test patch:
diff --git a/packages/kit/test/apps/options/source/hooks.server.js b/packages/kit/test/apps/options/source/hooks.server.js
index e69de29bb..0ca3568e9 100644
--- a/packages/kit/test/apps/options/source/hooks.server.js
+++ b/packages/kit/test/apps/options/source/hooks.server.js
@@ -0,0 +1,8 @@
+/** @type {import('@sveltejs/kit').Handle} */
+export function handle({ event, resolve }) {
+	return resolve(event, {
+		// this allows us to check that <link rel="stylesheet"> is still added
+		// to the DOM even if they're not included by `preload`
+		preload: ({ type }) => type !== 'css'
+	});
+}