Repository navigation
|
I've noticed what resolving a route that doesn't exist yields a different 404 page vs returning a 404 response in hooks.server.ts. Ideally I want those responses to look the same, for example not to "reveal" that the 404 was caused by anything else but the route not existing in case of a route that I want to protect with special permissions. Is it possible to have sveltekit handle the request as if the route doesn't exist? |
Replies: 1 comment
|
This is expected, and it's documented: SvelteKit renders errors differently depending on where they're thrown, not on the status code. Why they look different
Source, for anyone who wants to check (links point at the kit/packages/kit/src/runtime/server/respond.js Lines 412 to 427 in c6f9a78 kit/packages/kit/src/runtime/server/utils.js Lines 55 to 93 in c6f9a78 Errors thrown in kit/packages/kit/src/runtime/server/page/index.js Lines 260 to 335 in c6f9a78 This is also written up in the docs under "Responses": kit/documentation/docs/30-advanced/25-errors.md Lines 152 to 179 in c6f9a78 The fix Don't do the permission check (or the 404) in // src/routes/admin/+layout.server.ts
import { error } from '@sveltejs/kit';
export const load = async ({ locals }) => {
if (!locals.user?.isAdmin) {
error(404, 'Not Found');
}
// ...
};Thrown from
If you need something to run at the |
This is expected, and it's documented: SvelteKit renders errors differently depending on where they're thrown, not on the status code.
Why they look different
error(...)directly insidehandleinhooks.server.ts(or inside a+server.jshandler), gets the fallback error page (src/error.html, or SvelteKit's built-in default if you haven't added one). This never touches your+error.sveltecomponent tree.loadfunction (page or layout) bubbles up to the nearest+error.svelteabove it in the route tree, same as a normal SvelteKit "framework" 404 for an unmatched route (that one also renders via the r…