Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[breaking] add error.html #6367

Merged
merged 18 commits into from
Aug 30, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/quiet-camels-shop.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@sveltejs/kit': patch
---

[breaking] add `error.html` page, rename `kit.config.files.template` to `kit.config.files.appTemplate`
4 changes: 4 additions & 0 deletions documentation/docs/01-project-structure.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ my-project/
│ ├ routes/
│ │ └ [your routes]
│ ├ app.html
│ ├ error.html
│ └ hooks.js
├ static/
│ └ [your static assets]
Expand Down Expand Up @@ -41,6 +42,9 @@ The `src` directory contains the meat of your project.
- `%sveltekit.body%` — the markup for a rendered page. Typically this lives inside a `<div>` or other element, rather than directly inside `<body>`, to prevent bugs caused by browser extensions injecting elements that are then destroyed by the hydration process
- `%sveltekit.assets%` — either [`paths.assets`](/docs/configuration#paths), if specified, or a relative path to [`paths.base`](/docs/configuration#base)
- `%sveltekit.nonce%` — a [CSP](/docs/configuration#csp) nonce for manually included links and scripts, if used
- `error.html` (optional) is the page that is rendered when everything else fails. It can contain the following placeholders:
- `%sveltekit.status%` — the HTTP status
- `%sveltekit.message%` — the error message
- `hooks.js` (optional) contains your application's [hooks](/docs/hooks)
- `service-worker.js` (optional) contains your [service worker](/docs/service-workers)

Expand Down
2 changes: 1 addition & 1 deletion documentation/docs/03-routing.md
Original file line number Diff line number Diff line change
Expand Up @@ -190,7 +190,7 @@ If an error occurs during `load`, SvelteKit will render a default error page. Yo
<h1>{$page.status}: {$page.error.message}</h1>
```

SvelteKit will 'walk up the tree' looking for the closest error boundary — if the file above didn't exist it would try `src/routes/blog/+error.svelte` and `src/routes/+error.svelte` before rendering the default error page.
SvelteKit will 'walk up the tree' looking for the closest error boundary — if the file above didn't exist it would try `src/routes/blog/+error.svelte` and `src/routes/+error.svelte` before rendering the default error page. If _that_ fails, SvelteKit will bail out and render a static fallback error page, which you can customise by creating a `src/error.html` file.

### +layout

Expand Down
3 changes: 2 additions & 1 deletion documentation/docs/15-configuration.md
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,8 @@ const config = {
params: 'src/params',
routes: 'src/routes',
serviceWorker: 'src/service-worker',
template: 'src/app.html'
appTemplate: 'src/app.html',
errorTemplate: 'src/error.html'
},
inlineStyleThreshold: 0,
methodOverride: {
Expand Down
56 changes: 56 additions & 0 deletions packages/kit/src/core/config/default-error.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>%sveltekit.message%</title>

<style>
body {
font-family: system-ui, -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen,
Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif;
display: flex;
align-items: center;
justify-content: center;
height: 100vh;
}

.error {
display: flex;
align-items: center;
max-width: 32rem;
margin: 0 1rem;
}

.status {
font-weight: 200;
font-size: 3rem;
line-height: 1;
position: relative;
top: -0.05rem;
}

.message {
border-left: 1px solid #ccc;
padding: 0 0 0 1rem;
margin: 0 0 0 1rem;
min-height: 2.5rem;
display: flex;
align-items: center;
}

.message h1 {
font-weight: 400;
font-size: 1em;
margin: 0;
}
</style>
</head>
<body>
<div class="error">
<span class="status">%sveltekit.status%</span>
<div class="message">
<h1>%sveltekit.message%</h1>
</div>
</div>
</body>
</html>
29 changes: 24 additions & 5 deletions packages/kit/src/core/config/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,11 +10,11 @@ import options from './options.js';
* @param {import('types').ValidatedConfig} config
*/
export function load_template(cwd, config) {
const { template } = config.kit.files;
const relative = path.relative(cwd, template);
const { appTemplate } = config.kit.files;
const relative = path.relative(cwd, appTemplate);

if (fs.existsSync(template)) {
const contents = fs.readFileSync(template, 'utf8');
if (fs.existsSync(appTemplate)) {
const contents = fs.readFileSync(appTemplate, 'utf8');

// TODO remove this for 1.0
const match = /%svelte\.([a-z]+)%/.exec(contents);
Expand All @@ -34,7 +34,17 @@ export function load_template(cwd, config) {
throw new Error(`${relative} does not exist`);
}

return fs.readFileSync(template, 'utf-8');
return fs.readFileSync(appTemplate, 'utf-8');
}

/**
* Loads the error page (src/error.html by default) if it exists.
* Falls back to a generic error page content.
* @param {import('types').ValidatedConfig} config
*/
export function load_error_page(config) {
const { errorTemplate } = config.kit.files;
return fs.readFileSync(errorTemplate, 'utf-8');
}

/**
Expand Down Expand Up @@ -64,10 +74,19 @@ function process_config(config, { cwd = process.cwd() } = {}) {
validated.kit.outDir = path.resolve(cwd, validated.kit.outDir);

for (const key in validated.kit.files) {
// TODO remove for 1.0
if (key === 'template') continue;

// @ts-expect-error this is typescript at its stupidest
validated.kit.files[key] = path.resolve(cwd, validated.kit.files[key]);
}

if (!fs.existsSync(validated.kit.files.errorTemplate)) {
validated.kit.files.errorTemplate = url.fileURLToPath(
new URL('./default-error.html', import.meta.url)
);
}

return validated;
}

Expand Down
7 changes: 6 additions & 1 deletion packages/kit/src/core/config/index.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,9 @@ const get_defaults = (prefix = '') => ({
params: join(prefix, 'src/params'),
routes: join(prefix, 'src/routes'),
serviceWorker: join(prefix, 'src/service-worker'),
template: join(prefix, 'src/app.html')
appTemplate: join(prefix, 'src/app.html'),
errorTemplate: join(prefix, 'src/error.html'),
template: undefined
},
headers: undefined,
host: undefined,
Expand Down Expand Up @@ -381,6 +383,9 @@ test('load default config (esm)', async () => {

const defaults = get_defaults(cwd + '/');
defaults.kit.version.name = config.kit.version.name;
defaults.kit.files.errorTemplate = fileURLToPath(
new URL('./default-error.html', import.meta.url)
);

assert.equal(config, defaults);
});
Expand Down
7 changes: 6 additions & 1 deletion packages/kit/src/core/config/options.js
Original file line number Diff line number Diff line change
Expand Up @@ -140,7 +140,12 @@ const options = object(
params: string(join('src', 'params')),
routes: string(join('src', 'routes')),
serviceWorker: string(join('src', 'service-worker')),
template: string(join('src', 'app.html'))
appTemplate: string(join('src', 'app.html')),
errorTemplate: string(join('src', 'error.html')),
// TODO: remove this for the 1.0 release
template: error(
() => 'config.kit.files.template has been renamed to config.kit.files.appTemplate'
)
}),

// TODO: remove this for the 1.0 release
Expand Down
19 changes: 13 additions & 6 deletions packages/kit/src/exports/vite/build/build_server.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import fs from 'fs';
import path from 'path';
import { mkdirp, posixify } from '../../../utils/filesystem.js';
import { get_vite_config, merge_vite_configs, resolve_entry } from '../utils.js';
import { load_template } from '../../../core/config/index.js';
import { load_error_page, load_template } from '../../../core/config/index.js';
import { runtime_directory } from '../../../core/utils.js';
import { create_build, find_deps, get_default_build_config, is_http_method } from './utils.js';
import { s } from '../../../utils/misc.js';
Expand All @@ -14,22 +14,27 @@ import { s } from '../../../utils/misc.js';
* has_service_worker: boolean;
* runtime: string;
* template: string;
* error_page: string;
* }} opts
*/
const server_template = ({ config, hooks, has_service_worker, runtime, template }) => `
const server_template = ({ config, hooks, has_service_worker, runtime, template, error_page }) => `
import root from '__GENERATED__/root.svelte';
import { respond } from '${runtime}/server/index.js';
import { set_paths, assets, base } from '${runtime}/paths.js';
import { set_prerendering } from '${runtime}/env.js';
import { set_private_env } from '${runtime}/env-private.js';
import { set_public_env } from '${runtime}/env-public.js';

const template = ({ head, body, assets, nonce }) => ${s(template)
const app_template = ({ head, body, assets, nonce }) => ${s(template)
.replace('%sveltekit.head%', '" + head + "')
.replace('%sveltekit.body%', '" + body + "')
.replace(/%sveltekit\.assets%/g, '" + assets + "')
.replace(/%sveltekit\.nonce%/g, '" + nonce + "')};

const error_template = ({ status, message }) => ${s(error_page)
.replace(/%sveltekit\.status%/g, '" + status + "')
.replace(/%sveltekit\.message%/g, '" + message + "')};

let read = null;

set_paths(${s(config.kit.paths)});
Expand Down Expand Up @@ -78,8 +83,9 @@ export class Server {
root,
service_worker: ${has_service_worker ? "base + '/service-worker.js'" : 'null'},
router: ${s(config.kit.browser.router)},
template,
template_contains_nonce: ${template.includes('%sveltekit.nonce%')},
app_template,
app_template_contains_nonce: ${template.includes('%sveltekit.nonce%')},
error_template,
trailing_slash: ${s(config.kit.trailingSlash)}
};
}
Expand Down Expand Up @@ -205,7 +211,8 @@ export async function build_server(options, client) {
hooks: app_relative(hooks_file),
has_service_worker: config.kit.serviceWorker.register && !!service_worker_entry_file,
runtime: posixify(path.relative(build_dir, runtime_directory)),
template: load_template(cwd, config)
template: load_template(cwd, config),
error_page: load_error_page(config)
})
);

Expand Down
12 changes: 9 additions & 3 deletions packages/kit/src/exports/vite/dev/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import { getRequest, setResponse } from '../../../exports/node/index.js';
import { installPolyfills } from '../../../exports/node/polyfills.js';
import { coalesce_to_error } from '../../../utils/error.js';
import { posixify } from '../../../utils/filesystem.js';
import { load_template } from '../../../core/config/index.js';
import { load_error_page, load_template } from '../../../core/config/index.js';
import { SVELTE_KIT_ASSETS } from '../../../constants.js';
import * as sync from '../../../core/sync/sync.js';
import { get_mime_lookup, runtime_base, runtime_prefix } from '../../../core/utils.js';
Expand Down Expand Up @@ -371,6 +371,7 @@ export async function dev(vite, vite_config, svelte_config, illegal_imports) {
}

const template = load_template(cwd, svelte_config);
const error_page = load_error_page(svelte_config);

const rendered = await respond(
request,
Expand Down Expand Up @@ -416,7 +417,7 @@ export async function dev(vite, vite_config, svelte_config, illegal_imports) {
read: (file) => fs.readFileSync(path.join(svelte_config.kit.files.assets, file)),
root,
router: svelte_config.kit.browser.router,
template: ({ head, body, assets, nonce }) => {
app_template: ({ head, body, assets, nonce }) => {
return (
template
.replace(/%sveltekit\.assets%/g, assets)
Expand All @@ -426,7 +427,12 @@ export async function dev(vite, vite_config, svelte_config, illegal_imports) {
.replace('%sveltekit.body%', () => body)
);
},
template_contains_nonce: template.includes('%sveltekit.nonce%'),
app_template_contains_nonce: template.includes('%sveltekit.nonce%'),
error_template: ({ status, message }) => {
return error_page
.replace(/%sveltekit\.status%/g, String(status))
.replace(/%sveltekit\.message%/g, message);
},
trailing_slash: svelte_config.kit.trailingSlash
},
{
Expand Down
4 changes: 2 additions & 2 deletions packages/kit/src/runtime/client/client.js
Original file line number Diff line number Diff line change
Expand Up @@ -832,7 +832,7 @@ export function create_client({ target, base, trailing_slash }) {

// if we get here, it's because the root `load` function failed,
// and we need to fall back to the server
native_navigation(url);
await native_navigation(url);
return;
}
} else {
Expand Down Expand Up @@ -886,7 +886,7 @@ export function create_client({ target, base, trailing_slash }) {
server_data_node = server_data.nodes[0] ?? null;
} catch {
// at this point we have no choice but to fall back to the server
native_navigation(url);
await native_navigation(url);

// @ts-expect-error
return;
Expand Down
7 changes: 2 additions & 5 deletions packages/kit/src/runtime/server/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { render_page } from './page/index.js';
import { render_response } from './page/render.js';
import { respond_with_error } from './page/respond_with_error.js';
import { coalesce_to_error } from '../../utils/error.js';
import { serialize_error, GENERIC_ERROR } from './utils.js';
import { serialize_error, GENERIC_ERROR, static_error_page } from './utils.js';
import { decode_params, disable_search, normalize_path } from '../../utils/url.js';
import { exec } from '../../utils/routing.js';
import { negotiate } from '../../utils/http.js';
Expand Down Expand Up @@ -360,10 +360,7 @@ export async function respond(request, options, state) {
});
} catch (/** @type {unknown} */ e) {
const error = coalesce_to_error(e);

return new Response(options.dev ? error.stack : error.message, {
status: 500
});
return static_error_page(options, 500, error.message);
}
}
}
13 changes: 6 additions & 7 deletions packages/kit/src/runtime/server/page/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { devalue } from 'devalue';
import { negotiate } from '../../../utils/http.js';
import { render_response } from './render.js';
import { respond_with_error } from './respond_with_error.js';
import { method_not_allowed, error_to_pojo, allowed_methods } from '../utils.js';
import { method_not_allowed, error_to_pojo, allowed_methods, static_error_page } from '../utils.js';
import { create_fetch } from './fetch.js';
import { HttpError, Redirect } from '../../control.js';
import { error, json } from '../../../exports/index.js';
Expand Down Expand Up @@ -281,12 +281,11 @@ export async function render_page(event, route, page, options, state, resolve_op
}

// if we're still here, it means the error happened in the root layout,
// which means we have to fall back to a plain text response
// TODO since the requester is expecting HTML, maybe it makes sense to
// doll this up a bit
return new Response(
error instanceof HttpError ? error.message : options.get_stack(error),
{ status }
// which means we have to fall back to error.html
return static_error_page(
options,
status,
/** @type {HttpError | Error} */ (error).message
);
}
} else {
Expand Down
4 changes: 2 additions & 2 deletions packages/kit/src/runtime/server/page/render.js
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ export async function render_response({
throw new Error('Cannot use prerendering if config.kit.csp.mode === "nonce"');
}

if (options.template_contains_nonce) {
if (options.app_template_contains_nonce) {
throw new Error('Cannot use prerendering if page template contains %sveltekit.nonce%');
}
}
Expand Down Expand Up @@ -346,7 +346,7 @@ export async function render_response({
// TODO flush chunks as early as we can
const html =
(await resolve_opts.transformPageChunk({
html: options.template({ head, body, assets, nonce: /** @type {string} */ (csp.nonce) }),
html: options.app_template({ head, body, assets, nonce: /** @type {string} */ (csp.nonce) }),
done: true
})) || '';

Expand Down
6 changes: 2 additions & 4 deletions packages/kit/src/runtime/server/page/respond_with_error.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { render_response } from './render.js';
import { load_data, load_server_data } from './load_data.js';
import { coalesce_to_error } from '../../../utils/error.js';
import { GENERIC_ERROR } from '../utils.js';
import { GENERIC_ERROR, static_error_page } from '../utils.js';
import { create_fetch } from './fetch.js';

/**
Expand Down Expand Up @@ -87,8 +87,6 @@ export async function respond_with_error({ event, options, state, status, error,

options.handle_error(error, event);

return new Response(error.stack, {
status: 500
});
return static_error_page(options, 500, error.message);
}
}
Loading